简体   繁体   English

Webapi2返回ef对象

[英]Webapi2 returning ef object

I have a problem with entity framework object in a webapi project. 我在webapi项目中遇到实体框架对象的问题。 Since 2-3 days ago everything works fine, but now, the api I call always return "Out of memory exception". 从2-3天前开始,一切正常,但现在,我调用的api始终返回“内存不足异常”。

Initially I check for the classic "circular reference error" but is not the case. 最初,我检查经典的“圆形参考误差”,但事实并非如此。

In the webapi configuration I have this 在webapi配置中,我有这个

config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.None;
        config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.None;
        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

And to return ef object I use function like this 为了返回ef对象,我使用了这样的函数

public Contatti GetContatto([FromUri]int id)
    {
        var db=new WebEntities();
        return(db.Contatti.Single(x=>x.IDContatto == id));
    }

There's a way to return an ef object (with its subobject) in a json response with webapi2? 有一种方法可以使用webapi2在json响应中返回ef对象(及其子对象)?

I didn't really look at the code you've posted when I commented on your question, but now that I did I have some remarks: 在评论您的问题时,我并没有真正看过您发布的代码,但现在我有了一些评论:

Always call dispose , do not wait for the GC to clear memory. 始终调用dispose ,不要等待GC清除内存。 Though the "Out of Memory" exception may not be caused by this particular method, it is possible that you are also not disposing other (large) objects, like images. 尽管“内存不足”异常可能不是由此特定方法引起的,但有可能您还没有处理其他(大)对象,例如图像。 So review your code and dispose objects where possible. 因此,请检查您的代码并在可能的情况下处置对象。 Best way to prevent "Out of memory" exceptions. 防止“内存不足”异常的最佳方法。

    public Contatti GetContatto([FromUri]int id)
    {
        using(var db = new WebEntities())
        {
            return(db.Contatti.Single(x => x.IDContatto == id));
        }
    }

Is there a way to return an ef object (with its subobject) in a json response with webapi2? 有没有办法在webapi2的json响应中返回ef对象(及其子对象)?

Yes, but I would really recommend not to return EF objects but use DTO's instead. 是的,但是我真的建议不要返回EF对象,而应使用DTO Saves a lot of trouble! 省了很多麻烦!

To return an EF object, you'd better unproxy the object first: 要返回EF对象,最好先取消代理该对象:

    protected internal T UnProxyItem<T>(T proxyObject) where T : class
    {
        var proxyCreationEnabled = this.Configuration.ProxyCreationEnabled;
        try
        {
            this.Configuration.ProxyCreationEnabled = false;
            return this.Entry(proxyObject).CurrentValues.ToObject() as T;
        }
        finally
        {
            this.Configuration.ProxyCreationEnabled = proxyCreationEnabled;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM