C# JsonFormatter ReferenceLoopHandling
我已经为此挣扎了几天了,到目前为止,在我找到的任何解决方案中都找不到任何乐趣 该项目是使用实体框架6和WebAPI 2构建的。 我已将my WebApiConfig设置更改为C# JsonFormatter ReferenceLoopHandling,c#,json.net,entity-framework-6,asp.net-web-api2,C#,Json.net,Entity Framework 6,Asp.net Web Api2,我已经为此挣扎了几天了,到目前为止,在我找到的任何解决方案中都找不到任何乐趣 该项目是使用实体框架6和WebAPI 2构建的。 我已将my WebApiConfig设置更改为 config.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); config.Formatters.JsonFormatter.SerializerSettings.ReferenceL
config.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
现在似乎出现了一个无限循环,引发了系统内存不足异常
我似乎找不到做这件事的正确方法
我也在WebAPI方法中尝试过这一点,但症状仍然相同
public async Task<IHttpActionResult> GetCustomer_Title(int id)
{
Customer_Title c = await db.Customer_Title.FindAsync(id);
if (c == null)
{
return NotFound();
}
var json = JsonConvert.SerializeObject(c, new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return Ok(json);
}
public异步任务GetCustomer\u Title(int-id)
{
Customer\u Title c=等待db.Customer\u Title.FindAsync(id);
如果(c==null)
{
返回NotFound();
}
var json=JsonConvert.SerializeObject(c,新的JsonSerializerSettings()
{
ReferenceLoopHandling=ReferenceLoopHandling.Ignore
});
返回Ok(json);
}
在我的客户课程中
public partial class Customer_Title
{
public Customer_Title()
{
Customer = new HashSet<Customer>();
}
[Key]
public int TitleID { get; set; }
[Required]
[StringLength(100)]
public string TitleDescription { get; set; }
public int InstanceID { get; set; }
[JsonIgnore]
public virtual ICollection<Customer> Customer { get; set; }
public virtual System_Instance System_Instance { get; set; }
}
公共部分类客户\u标题
{
公共客户名称()
{
Customer=newhashset();
}
[关键]
公共int TitleID{get;set;}
[必需]
[长度(100)]
公共字符串标题说明{get;set;}
public int InstanceID{get;set;}
[JsonIgnore]
公共虚拟ICollection客户{get;set;}
公共虚拟系统\实例系统\实例{get;set;}
}
[JsonIgnore]属性似乎没有任何作用。您应该使用DTO而不是实体框架实体, 例如:
class PersonDTO {
public Name {get; set;}
}
var person = context.People.First();
var personDTO = new PersonDTO{
Name = person.Name
}
var json = new JavaScriptSerializer().Serialize(personDTO);
这是唯一的办法吗?如果没有中间DTO,他们就无法做到这一点吗?对于web api,您不需要DTO,web api可以处理它,我认为这不是一个答案-即使用不同的对象!您可能还应该禁用延迟加载。我认为整个粘附实体的舰队是从数据库中拖入的。禁用延迟加载也没有帮助