2016-11-27 9 views
0

私は3つのEntityクラスを持っています。Entity Frameworkのクエリに問題があります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); 

    } 

これは問題ありません。問題は、各地域の都市の名前も取得したいということです。私はLocationテーブルからcityIDを取得していますが、LocationエンティティのCityプロパティはnullを返しています。なぜそれがnullですか?都市名を取得するためにクエリを変更するにはどうすればよいですか?どんなヒントも非常に高く評価されます。

答えて

1

置き換えます

.Include(p => p.Locations) 

で:EFコアで

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

をあなたも行います

.Include(p => p.Locations) 
    .ThenInclude(l => l.City) 
関連する問題