C# Webapi2返回ef对象

C# Webapi2返回ef对象,c#,entity-framework,C#,Entity Framework,我对webapi项目中的实体框架对象有问题。 从2-3天前开始,一切正常,但现在,我调用的api总是返回“内存不足异常” 最初我检查经典的“循环参考错误”,但事实并非如此 在webapi配置中,我有 config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.None; config.Formatters.JsonFormatter.SerializerSetting

我对webapi项目中的实体框架对象有问题。 从2-3天前开始,一切正常,但现在,我调用的api总是返回“内存不足异常”

最初我检查经典的“循环参考错误”,但事实并非如此

在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"));
为了返回ef对象,我使用如下函数

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

有一种方法可以在webapi2的json响应中返回ef对象(及其子对象)

我在对您的问题发表评论时并没有真正看过您发布的代码,但现在我看到了,我有一些评论:

始终调用dispose,不要等待GC清除内存。虽然“内存不足”异常可能不是由此特定方法引起的,但也可能是您没有处理其他(大型)对象,如图像。因此,请检查您的代码,并尽可能处理对象。防止“内存不足”异常的最佳方法

    public Contatti GetContatto([FromUri]int id)
    {
        using(var db = new WebEntities())
        {
            return(db.Contatti.Single(x => x.IDContatto == id));
        }
    }
有没有办法在webapi2的json响应中返回ef对象(及其子对象)

是的,但我确实建议不要返回EF对象,而是使用DTO。省去了很多麻烦

要返回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;
        }
    }
受保护的内部T未经验证的项(T proxyObject),其中T:class
{
var proxycreasonenabled=this.Configuration.proxycreasonenabled;
尝试
{
this.Configuration.ProxyCreationEnabled=false;
将此.Entry(proxyObject).CurrentValues.ToObject()作为T返回;
}
最后
{
this.Configuration.ProxyCreationEnabled=ProxyCreationEnabled;
}
}

是什么让您认为“内存不足”异常是由EF6对象生成json引起的?您是否检查了服务器上的内存使用情况?你在处理大型物体吗?重新启动网站时,是否仍会出现此异常?OOM可能是由其他方法引起的。当您调用GetContatto方法时,专用于应用程序池的内存已经耗尽,它最终引发异常。
Always call dispose
Always是一个强有力的词。如果我们使用Repository和Unit of Work模式,我们不应该在每个方法中处理DbContext。为了解决这个问题,我使用了DTO、Repository和Unit of Work模式,所以一切都很正常。这个问题只是出于好奇,因为两天前returniung ef object正在工作:)