我在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对象(及其子对象)?
发布于 2017-02-10 00:38:04
当我对你的问题发表评论时,我并没有真正看过你发布的代码,但现在我已经看了,我有一些评论:
始终调用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;
}
}https://stackoverflow.com/questions/42139898
复制相似问题