C# “卸载”;“急迫的加载”;返回json'时导致问题的属性;d数据

C# “卸载”;“急迫的加载”;返回json'时导致问题的属性;d数据,c#,json,eager-loading,asp.net-web-api2,C#,Json,Eager Loading,Asp.net Web Api2,希望这个标题有意义,我会尽力描述我的问题 我目前正在开发一个ASP.NET Web API。在我的“公司”控制器中,我有一个GetCompany()操作 // ///获取“授权令牌”请求标头,并查找具有 ///匹配数据库中解密的令牌,返回该令牌;如果为null,则返回404 /// ///为传入请求的令牌或404(如果为空)匹配公司 [HttpGet][ResponseType(公司类型))] [路线(“api/公司/”)] 公共HttpResponseMessage GetCompany()

希望这个标题有意义,我会尽力描述我的问题

我目前正在开发一个ASP.NET Web API。在我的“公司”控制器中,我有一个GetCompany()操作

//
///获取“授权令牌”请求标头,并查找具有
///匹配数据库中解密的令牌,返回该令牌;如果为null,则返回404
/// 
///为传入请求的令牌或404(如果为空)匹配公司
[HttpGet][ResponseType(公司类型))]
[路线(“api/公司/”)]
公共HttpResponseMessage GetCompany(){
string token=Request.Headers.GetValues(“授权令牌”).First();
i收集公司;
c公司;
使用(BaseRepository r=new BaseRepository()){
companys=r.Get(null,null,null);
c=companys.Where(cm=>RSA.Decrypt(cm.Token)==Token.FirstOrDefault();
}
如果(c==null)
返回请求.CreateResponse(HttpStatusCode.NotFound,c);
返回请求.CreateResponse(HttpStatusCode.OK,c);
}
这会找到它并返回它,但是当我测试它时,我看到的响应是

{
    "Message": "An error has occurred.",
    "ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
    "ExceptionType": "System.InvalidOperationException",
    "StackTrace": null,
    "InnerException": {
        "Message": "An error has occurred.",
        "ExceptionMessage": "Error getting value from 'Locations' on 'System.Data.Entity.DynamicProxies.Company_40636FF93138F09772BEA689D3A3D3AB7DBB41AFF7FE3D0BEFF55FC7C1D10E0F'.",
        "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.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.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n   at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext)\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__14.MoveNext()",
        "InnerException": {
            "Message": "An error has occurred.",
            "ExceptionMessage": "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.",
            "ExceptionType": "System.ObjectDisposedException",
            "StackTrace": "   at System.Data.Entity.Core.Objects.ObjectContext.get_Connection()\r\n   at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\n   at System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)\r\n   at System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption)\r\n   at System.Data.Entity.Core.Objects.DataClasses.EntityCollection`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`2.<GetInterceptorDelegate>b__1(TProxy proxy, TItem item)\r\n   at System.Data.Entity.DynamicProxies.Company_40636FF93138F09772BEA689D3A3D3AB7DBB41AFF7FE3D0BEFF55FC7C1D10E0F.get_Locations()\r\n   at GetLocations(Object )\r\n   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"
        }
    }
}
{
“消息”:“发生错误。”,
“ExceptionMessage”:“ObjectContent'1'类型未能序列化内容类型'application/json;charset=utf-8'的响应正文。”,
“异常类型”:“System.InvalidOperationException”,
“StackTrace”:空,
“内部异常”:{
“消息”:“发生错误。”,
“异常消息”:“从'System.Data.Entity.DynamicProxies.Company_40636FF93138F09772BEA689D3A3D3AB7DBB41AF7FE3D0BEFF55FC7C1D10E0F'上的'Locations'获取值时出错。”,
“ExceptionType”:“Newtonsoft.Json.JsonSerializationException”,
“StackTrace”:“位于Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(对象目标)\r\n位于Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter编写器、对象值、JsonContainerContract、JsonProperty成员、JsonProperty属性、JsonContract和memberContract、对象和memberValue)\r\n位于Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter编写器,对象值,JsonObjectContract契约,JsonProperty成员,JsonContainerContract集合契约,JsonProperty容器属性)\r\n位于Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter编写器,对象值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\r\n位于Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter JsonWriter,对象值,类型objectType)\r\n位于Newtonsoft.Json.JsonSerializer.serializer\n(JsonWriter JsonWriter,Object value,Type objectType)\r\n位于Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter JsonWriter,Object value)\r\n位于System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type Type,Object value,Stream writeStream,HttpContent)\r\n在System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStreamAsync(类型类型、对象值、流writeStream、HttpContent内容、TransportContext TransportContext-TransportContext)\r\n---从引发异常的上一个位置开始的堆栈结束跟踪---\r\n在System.Runtime.CompilerServices.TaskWaiter.ThrowForOnSuccess(任务任务)\r\n在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)\r\n在System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n在System.Web.Http.WebHost.HttpControllerHandler.d_14.MoveNext()“,
“内部异常”:{
“消息”:“发生错误。”,
“ExceptionMessage”:“ObjectContext实例已被释放,不能再用于需要连接的操作。”,
“ExceptionType”:“System.ObjectDisposedException”,
“StackTrace”:“at System.Data.Entity.Core.Objects.ObjectContext.get_Connection()\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption MergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load”(列出System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(MergeOption MergeOption)\r\n System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.Load()\r\n System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()\r\n位于System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue,String relationshipName,String targetRoleName,Boolean mustBeNull,Object wrapperObject)\r\n位于System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.c_uDisplayClass7`2.b_uu1(TProxy代理,TItem项)\r\n位于System.Data.Entity.DynamicProxies.Company_40636FF93138F09772BEA689D3A3D3AB7DBB41AF7FE3D0BEFF55FC7C1D10E0F.get\n Locations()\r\n位于GetLocations(对象)\r\n位于Newtonsoft.Json.Serialization.DynamicValue Provider.GetValue(对象目标)
}
}
}
我知道问题是我的属性被急切地加载,而它们从来没有被加载过。我可以很容易地告诉它在我的
公司
对象中加载我的导航属性。当我这样做时,我遇到的问题是,上面提到的导航属性中的复杂对象也是空的我不能轻易地加载它们,我也不想加载。所以它试图加载整个“对象树”,因为没有更好的方式来表达它(我能想到)


所以我的问题是,解决这个问题的最佳方法是什么?

代理导致序列化程序尝试访问导航属性,这些属性由于上下文已更改而不再可用
{
    "Message": "An error has occurred.",
    "ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
    "ExceptionType": "System.InvalidOperationException",
    "StackTrace": null,
    "InnerException": {
        "Message": "An error has occurred.",
        "ExceptionMessage": "Error getting value from 'Locations' on 'System.Data.Entity.DynamicProxies.Company_40636FF93138F09772BEA689D3A3D3AB7DBB41AFF7FE3D0BEFF55FC7C1D10E0F'.",
        "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.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.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n   at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext)\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__14.MoveNext()",
        "InnerException": {
            "Message": "An error has occurred.",
            "ExceptionMessage": "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.",
            "ExceptionType": "System.ObjectDisposedException",
            "StackTrace": "   at System.Data.Entity.Core.Objects.ObjectContext.get_Connection()\r\n   at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\n   at System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)\r\n   at System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption)\r\n   at System.Data.Entity.Core.Objects.DataClasses.EntityCollection`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`2.<GetInterceptorDelegate>b__1(TProxy proxy, TItem item)\r\n   at System.Data.Entity.DynamicProxies.Company_40636FF93138F09772BEA689D3A3D3AB7DBB41AFF7FE3D0BEFF55FC7C1D10E0F.get_Locations()\r\n   at GetLocations(Object )\r\n   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"
        }
    }
}
 context.Configuration.ProxyCreationEnabled = false;
 context.Configuration.LazyLoadingEnabled = false;