【问题标题】:error when trying to get entity related to entity in webapi 2尝试获取与 webapi 2 中的实体相关的实体时出错
【发布时间】:2014-09-24 13:37:16
【问题描述】:

型号:

public class Dog
    {
        [Key, DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }

        [Required]
        public string Name { get; set; }

        public DateTime? Birthdate { get; set; }

        public string Color { get; set; }

        public string Race { get; set; }

        public string ChipNumber { get; set; }

        public byte[] Photo { get; set; }



        public virtual ICollection<Record> Records { get; set; }

        public virtual User User { get; set; }

    }

public class Record
    {
        public Record()
        {
            Quota = 1;
        }

        [Key, DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }

        public DateTime? Time { get; set; }

        [Required]
        public string Name { get; set; }

        public string Supplier { get; set; }

        public double? Price { get; set; }

        public int Quota { get; set; }

        public string Note { get; set; }



        public virtual Dog Dog { get; set; }

        public virtual User User { get; set; }
    }

WebapiConfig.cs:

var json = config.Formatters.JsonFormatter;
            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
            config.Formatters.Remove(config.Formatters.XmlFormatter);

在 webapi 中调用“api/dogs”会引发异常:

{"$id":"1","Message":"发生错误。","ExceptionMessage":"The 'ObjectContent1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"$id":"2","Message":"An error has occurred.","ExceptionMessage":"Error getting value from 'Records' on 'System.Data.Entity.DynamicProxies.Dog_2EE5CBDAE5320B6E973C971E716C24610E64BF4CECE05B6719C5876F271BA911'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":" at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()","InnerException":{"$id":"3","Message":"An error has occurred.","ExceptionMessage":"An error occurred while executing the command definition. See the inner exception for details.","ExceptionType":"System.Data.Entity.Core.EntityCommandExecutionException","StackTrace":" at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)\r\n at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)\r\n at System.Data.Entity.Core.Objects.ObjectQuery1.c__DisplayClass7.b__6()\r\n 在 System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)\r\n at System.Data.Entity.Core.Objects.ObjectQuery1.c__DisplayClass7.b__5()\r\n 在 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation)\r\n at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption)\r\n at System.Data.Entity.Core.Objects.ObjectQuery1.Execute(MergeOption 合并选项)\r\n 在 System.Data.Entity.Core.Objects.DataClasses.EntityCollection1.Load(List1 集合,MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.EntityCollection1.Load(MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.Load()\r\n at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()\r\n at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)\r\n at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass72.b__1(TProxy 代理,TItem 项)\r\n 在 System.Data.Entity.DynamicProxies.Dog_2EE5CBDAE5320B6E973C971E716C24610E64BF4CECE05B6719C5876F271BA911.get_Records()\r\n 在 GetRecords(对象)\r\n 在 Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)","InnerException":{"$id":"4","Message":"出现错误 发生。","ExceptionMessage":"已经有一个打开的 DataReader 与必须关闭的此命令相关联 首先。","ExceptionType":"System.InvalidOperationException","StackTrace":" 在 System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand 命令)\r\n 在 System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(字符串 方法,SqlCommand 命令)\r\n 在 System.Data.SqlClient.SqlCommand.ValidateCommand(字符串方法, 布尔异步)\r\n 在 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior、RunBehavior、runBehavior、布尔返回流、字符串 方法,TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite)\r\n at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)\r\n at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)\r\n at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)\r\n at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext1 c)\r\n at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func3 操作,TInterceptionContext 拦截上下文, Action3 executing, Action3 已执行)\r\n at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand 命令,DbCommandInterceptionContext 拦截上下文)\r\n 在 System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior 行为)\r\n 在 System.Data.Common.DbCommand.ExecuteReader(CommandBehavior 行为)\r\n 在 System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior 行为)"}}}}

【问题讨论】:

  • 我在使用可为空的日期时间值时遇到了类似的问题。如果这是一个获取请求,您是否可以尝试将 DateTime 属性设置为有效的日期时间值,然后再将其映射到 json 对象?例如 DateTime.Now?或者无论这些属性是否为空都会发生这种情况?
  • 我没有其他选择。这些属性必须可以为空,否则我无法执行update-database 命令
  • 我明白,我只是要求你做例如 Time = DateTime.Now 在返回结果之前只是看看它是否成功,因为有时日期可能超出范围。例如,如果由于某种原因将日期设置为 0/0 0000 00:00:00 而不是 null,这可能会搞砸。
  • 我创建了一个 DTO 并返回了我需要的部分类。我使用 LINQ 从数据库初始化 DTO 类。但我如何设置一个列表? from d in db.Dogs select new DogDTO() { Birthdate = DateTime.Now, ChipNumber = d.ChipNumber, Color = d.Color, Id = d.Id, Name = d.Name, Photo = d.Photo, Race = d.Race, UserId = d.User.Id, RecordsIDs = ???? };
  • RecordsIds = 新列表();

标签: entity-framework-6 asp.net-web-api2


【解决方案1】:

解决了。

创建 DOG 的 DTO 并在 DOGDTO 中返回 USER 和 RECORDS 现在返回 UserId 和 RecordIds 列表

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-03
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    相关资源
    最近更新 更多