【问题标题】:Entity Framework trouble querying ManyToMany relationship [duplicate]实体框架查询多对多关系时遇到问题[重复]
【发布时间】:2017-04-11 00:56:08
【问题描述】:

我有三个实体类。

public partial class Person
{
    public Person()
    {
        this.Locations = new HashSet<Location>();           
    }    
    public int PersonID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Location> Locations { get; set; }       
}

public partial class Location
{       
    public Location()
    {            
        this.People = new HashSet<Person>();
    }

    public int LocationID { get; set; }
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public int CityID { get; set; }           
    public virtual City City { get; set; }                    
    public virtual ICollection<Person> People { get; set; }
}

public partial class City
{
    public City()
    {
        this.Locations = new HashSet<Location>();
    }    
    public int CityID { get; set; }
    public string Name { get; set; }                         
    public virtual ICollection<Location> Locations { get; set; }
}

我正在尝试查询我的实体并获取给定人员的所有位置。 到目前为止我有这个方法。

public IQueryable<Person> GetLocationsForPerson(int id)
    {
        return context.People
                .Include(p => p.Locations)
                .Where(p => p.PersonID == id);

    }

这工作正常。问题是我也想获取每个位置的城市名称。当我从 Location 表中获取 cityID 时, Location 实体的 City 属性返回 null。为什么那是空的?以及如何修改我的查询以获取城市名称?任何提示将不胜感激。

【问题讨论】:

    标签: entity-framework linq


    【解决方案1】:

    替换:

    .Include(p => p.Locations)
    

    与:

    .Include(p => p.Locations.Select(l => l.City))
    

    在 EF Core 中,您也可以这样做:

    .Include(p => p.Locations)
       .ThenInclude(l => l.City)
    

    【讨论】:

      猜你喜欢
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-13
      • 2016-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多