实体框架麻烦查询Manytomany关系



我有三个实体类。

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

正常工作。问题是我也想在每个位置获取城市的名称。当我从位置表获得CityID时,位置实体的城市财产正在返回空。为什么那个零?我该如何修改我的查询以获取城市名称?任何提示都将不胜感激。

替换:

.Include(p => p.Locations)

with:

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

在EF核心中,您也要做:

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

最新更新