【发布时间】:2020-02-03 19:11:44
【问题描述】:
我正试图将所有汽车都交给车主。一位车主可以拥有多辆汽车,一辆汽车可以注册给一位车主。
如果我输入这样的查询,我会得到预期的结果:
public List<Owner> Get()
{
var ownerWithCars = db.Owner.Include(o => o.Cars).AsNoTracking().ToList();
return ownerWithCars;
}
但是这个查询不起作用:
public List<Owner> Get()
{
var cars = from o in db.Owners join c in db.Cars on o.Id equals c.OwnerId into cars
select new Owner() {Id = o.Id, Address = o.Address, Cars = cars.ToList()};
return cars;
}
如果我运行第二个查询,我会收到以下错误:
"ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
我已将以下内容添加到我的global.asax
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
【问题讨论】:
-
可能与错误无关;假设 Car 有主键 ID,
o.Id equals c.Id不应该是o.Id equals c.OwnerId -
哦,是的,我编辑了我的查询几次,最后一次我忘记输入 c.OwnerId 而不是 c.Id。
标签: c# asp.net model-view-controller webapi