实体框架在查询ManyToMany关系时遇到麻烦

时间:2016-11-27 01:55:13

标签: entity-framework linq

我有三个实体类。

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。为什么这是空的?以及如何修改我的查询以获取城市名称?任何提示都将不胜感激。

1 个答案:

答案 0 :(得分:1)

替换:

.Include(p => p.Locations)

使用:

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

在EF Core中你也可以:

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