2015-01-09 34 views
2

這是我的數據模型的例子:在多對多的關係中,你如何防止往返? - 實體框架

public class House : Record 
{ 
    public string HouseNumber { get; set; } 
    public string StreetName { get; set; } 
    public int ZipCode { get; set; } 

    public virtual ICollection<Street> Streets { get; set; } 
} 

public class Street 
{ 
    public int StreetId { get; set; } 
    public string StreetName { get; set; } 

    public virtual ICollection<House> HouseUnit { get; set; } 
    public virtual ICollection<House> HouseUnitParallel { get; set; } 
} 

我想只獲得StreetId和StreetName從街道(不含HouseUnit和HouseUnitParallel)每家的紀錄。

var entities = context.Houses.Include(r => r.Streets.Select(s => new 
{ 
    StreetId = s.StreetId, 
    StreetName = s.StreetName 
})); 

此代碼引發以下異常:

The Include path expression must refer to a navigation property defined on the type. 
Use dotted paths for reference navigation properties and the Select operator 
for collection navigation properties. 

每家記錄,我想排除我的街道物業內的HouseUnit和HouseUnitParallel集合(因爲它捎帶了一堆房子來我的房子紀錄)。

我能做些什麼來解決這個問題?

回答

-1

我想你想要這樣的:

var entities = context.Houses 
         .Include(r => r.Streets) 
         .SelectMany(h => h.Streets 
             .Select(s => new 
             { 
              StreetId = s.StreetId, 
              StreetName = s.StreetName 
             })); 

只要你延遲加載禁用的其他地方,你的虛擬ICollections不會急於加載除非Include'd沒有; HouseUnit和HouseUnitParallel應該被排除在外。

編輯:

看你的代碼再次導致異常,這可能是因爲你只是過思前想:排除HouseUnit和HouseUnitParallel,你根本就沒有Include他們:

var entities = context.Houses.Include(r => r.Streets); 

這再次將–,假設你沒有延遲加載其他地方禁止–包括Streets在一套House小號回來了,但不是關係上Street ;與

var entities = context.Houses 
         .Include(r => r.Streets.Select(s => s.HouseUnits)) 
         .Include(r => r.Streets.Select(s => s.HouseUnitParallel)); 

包括所有的關係對比這一點。

如果您嘗試前者,並且您仍然獲得所有關係,則應查看項目中其他位置是否已禁用延遲加載(即LazyLoadingEnabled = false)。即使有,您應該可以通過在LINQ查詢之前調用context.Configuration.LazyLoadingEnabled = true來爲此context範圍啓用它。

+1

然後你會得到只有街道回來作爲匿名類型忽略所有的房屋屬性,擊敗連接的目的。 – eugenekgn

+0

@eugenekgn - OP似乎只想要屬性StreetId和StreetName(我怎麼知道的?他說「我想只獲得StreetId和StreetName」......另外,他的嘗試解決方案只返回了「Select ')。他還出現了一個匿名類型的內容(同樣,因爲他的解決方案在'Select'中返回了一個匿名類型)。 –

+0

這可能是我誤解了OP想要做的 - 我會編輯我的答案。 –