【问题标题】:Include works but Join is not working c# linq包括工作,但加入不工作 c# linq
【发布时间】: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


【解决方案1】:

使用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 ;
}

【讨论】:

  • 你试过另一个吗? var ownerWithCars = (from o in db.Owners join c in db.Cars on o.Id equals c.OwnerId select o).Distinct().ToList();
  • 我首先使用public ICollection&lt;Car&gt; Cars {get; set;},然后我得到cars:null,当我将其更改为public virtual ICollection&lt;Car&gt; Cars {get; set;}时,我得到了您提到的查询结果。可能是我没有将虚拟属性放入导航属性的问题吗?
  • 我的荣幸。乐意效劳。请删除一些不相关的聊天内容,以便将来的用户使用。我将添加virtual 部分作为回答的注释。
猜你喜欢
  • 1970-01-01
  • 2014-12-22
  • 2011-12-02
  • 1970-01-01
  • 2017-10-22
  • 2014-07-20
  • 2013-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多