包含有效但加入无效 c# linq

Include works but Join is not working c# linq

我正在尝试与车主一起购买所有汽车。一个车主可以拥有多辆车,一辆车可以注册一个车主。

如果我输入这样的查询,我会得到预期的结果:

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);

您使用 Include 的第一个查询获得的结果集可以通过稍微不同地编写您的第二个查询来使用 join 获得。你可以试试:

public List<Owner> Get()
{
    var ownerWithCars = (from o in db.Owners
                join c in db.Cars on o.Id equals c.OwnerId into cars 
                select o).ToList();

    return ownerWithCars ;
}