卸载“渴望装载"的装载机.属性会在返回JSON数据时引起问题 [英] Unloaded "eager-loaded" properties causing issues when returning json'd data

查看:107
本文介绍了卸载“渴望装载"的装载机.属性会在返回JSON数据时引起问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hopefully the title makes sense, I'll do my best to describe my problem.

我目前正在开发ASP.NET Web API.在公司"控制器中,我有一个GetCompany()动作.

I'm currently developing an ASP.NET Web API. In my "Company" controller I have a GetCompany() action.

    /// <summary>
    /// Gets the 'Authorization-Token' request header and finds the company with the
    /// matching decrypted token from the database, returns it; if null, returns 404
    /// </summary>
    /// <returns>Matching company for token passed in request or 404 if null</returns>
    [HttpGet][ResponseType(typeof(Company))]
    [Route("api/company/")]
    public HttpResponseMessage GetCompany() {
        string token = Request.Headers.GetValues("Authorization-Token").First();

        ICollection<Company> companies;
        Company c;
        using (BaseRepository r = new BaseRepository()) {
            companies = r.Get<Company>(null, null, null);
            c = companies.Where(cm => RSA.Decrypt(cm.Token) == token).FirstOrDefault<Company>();
        }
        if (c == null)
            return Request.CreateResponse(HttpStatusCode.NotFound, c);

        return Request.CreateResponse(HttpStatusCode.OK, c);
    }

找到并返回它很好,但是当我测试它时,我看到的响应是

This finds it and returns it just fine, however when I'm testing this, the response I see is

{
    "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)"
        }
    }
}

我知道问题是我的属性已被急切加载,而它们从未被加载过.我可以告诉它很容易地将导航属性加载到我的Company对象中.我这样做时遇到的问题是,这些导航属性中的复杂对象也为null,因此我不能轻易地加载它们.我也不想.因此,由于缺乏一种更好的表达方式(我能想到的),它试图加载整个对象树".

I understand the problem is that my properties are eager-loaded and they aren't ever loaded. I can tell it to load my navigation properties inside my Company object quite easily. The problem I'm encountering when I do that, is that it's saying the complex objects inside of those aforementioned navigation properties are null as well and I can't so easily eager load them; nor do I want to. So it's attempting to load the whole "object tree" for lack of a better way to say it (that I can think of).

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

So my question is, what is the best way to get around this?

推荐答案

代理使序列化程序尝试访问导航属性,这些导航属性由于处理了上下文而不再可用.

The proxy is causing the serializer to attempt to access navigational properties which are no longer available since the context has been disposed.

在查询要序列化的对象时,请尝试从上下文中删除代理并急于加载

Try removing the proxy and eager loading from your context when you are querying for objects that will be serialized

 context.Configuration.ProxyCreationEnabled = false;
 context.Configuration.LazyLoadingEnabled = false;

这篇关于卸载“渴望装载"的装载机.属性会在返回JSON数据时引起问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆