尝试在web api 2中获取与实体相关的实体时出错

时间:2014-09-24 13:37:16

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

型号:

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中呼叫&#39; api / dogs&#39;抛出异常:

  

{&#34; $ id&#34;:&#34; 1&#34;,&#34;消息&#34;:&#34;发生错误。&#34;,&#34; &ExceptionMessage#34;:&#34;该   &#39; {ObjectContent {1}} 1&LT;&GT; c__DisplayClass7.b__6(个)\ r \ n   在   System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction [T](Func键1' 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.ObjectQuery 1&LT;&GT; c__DisplayClass7.b__5(个)\ r \ n   在   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute [TResult](Func键{{1} 1.GetResults(可为空的1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)\r\n at System.Data.Entity.Core.Objects.ObjectQuery 1.Execute(MergeOption   mergeOption)\ r \ n at   System.Data.Entity.Core.Objects.DataClasses.EntityCollection 1 operation)\r\n at System.Data.Entity.Core.Objects.ObjectQuery 1   集合,MergeOption mergeOption)\ r \ n at   System.Data.Entity.Core.Objects.DataClasses.EntityCollection 1 forMergeOption)\r\n at System.Data.Entity.Core.Objects.ObjectQuery 2.b__1(TProxy   代理,TItem项目)\ r \ n at   System.Data.Entity.DynamicProxies.Dog_2EE5CBDAE5320B6E973C971E716C24610E64BF4CECE05B6719C5876F271BA911.get_Records(个)\ r \ n   在GetRecords(对象)\ r \ n at   Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(对象   目标)&#34;&#34;的InnerException&#34; {&#34; $ ID&#34;:&#34; 4&#34;&#34;消息&#34;:&#34;安错误有   发生了。&#34;,&#34; ExceptionMessage&#34;:&#34;已经有一个开放的DataReader   与此命令关联,必须关闭   。第一&#34;&#34; ExceptionType&#34;:&#34; System.InvalidOperationException&#34;&#34;堆栈跟踪&#34;:&#34;   在   System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand的   命令)\ r \ n at   System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(字符串   方法,SqlCommand命令)\ r \ n at   System.Data.SqlClient.SqlCommand.ValidateCommand(String方法,   布尔异步)\ r \ n at   System.Data.SqlClient.SqlCommand.RunExecuteReader(的CommandBehavior   cmdBehavior,RunBehavior runBehavior,Boolean returnStream,String   方法,TaskCompletionSource 1.Load(List 1 c)\ r \ n at   System.Data.Entity.Infrastructure.Interception.InternalDispatcher 1.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__DisplayClass7 3操作,TInterceptionContext interceptionContext,   行动1 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, DbCommandInterceptionContext 3已执行)\ r \ n at   System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(的DbCommand   command,DbCommandInterceptionContext interceptionContext)\ r \ n at   System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(的CommandBehavior   行为)\ r \ n at   System.Data.Common.DbCommand.ExecuteReader(的CommandBehavior   行为)\ r \ n at   System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand   entityCommand,CommandBehavior行为)&#34;}}}}

1 个答案:

答案 0 :(得分:1)

解决。

创建了DOG的DTO并且在DOGDTO中返回了一个USER和RECORDS它现在返回UserId和RecordIds列表