2012-10-22 34 views
1

所以我用EF,我有以下實體:LINQ查詢檢索項

  • Website
  • Sector
  • Product
  • Attribute
  • AttributeTag

的相對ationships如下:

enter image description here

我需要找回的東西,沒有直接的聯繫表。例如需要Sector對象的產品才能使用諸如sector.Products之類的內容來檢索特定的Products

但是如果我需要檢索給定的Website下的所有Products而不是它的父Sector

在我的具體情況,我的問題是: 1)我如何可以檢索給出了具體的website_id所有的產品 - )(不考慮部門 2)我怎樣才能檢索到所有具有特定tag_id + website_id產品。 (也檢索它的相應Attribute

幫助表示讚賞。謝謝!

+0

好的,我會刪除它。 :) – user1027620

回答

2

假設你有兩個側面導航屬性:

你將不得不在產品實體List<Sector> SectorList

您將在扇區實體中有一個List<Product> ProductList

sectors_products將不會作爲實體存在,因爲它在對象世界中不需要)。

你將不得不在部門實體Website Website

你將不得不在產品實體List<AttributeTag> AttributeTagList;

products_tags將不會作爲實體存在,因爲它在對象世界中不需要)。

1)類似:

var result = ProductEntities 
      .Where(p => p.SectorList 
         .Any(s => s.WebSite.Id == <your_website_id>) 
        ); 

2)像(取1)基本查詢)

result = result 
     .Where(p => p.AttributeTagList 
        .Any(at => at.Id == <your_tag_id>) 
       ); 

或全部在一個

var result = ProductEntitites 
       .Where(p => 
         p.SectorList.Any(s => s.WebSite.Id == <your_website_id>) && 
         p.AttributeTagList.Any(at => at.Id == <your_tag_id>) 
        ); 
1

的關係在你的架構形成一條途徑。如果你想弄清楚兩個實體集合之間的關係,你必須遵循這個途徑並查詢其間的所有實體。

var part1 = (from w in Websites 
      from s in Sectors 
      from p in s.Products 
      where s.Website equals w 
      && w.website_id equals web_id 
      select p).Distinct(); 

var part2 = from p in part1 
      let attr = p.Attributes.Where(a => a.tag_id + web_id == target_val) 
      where attr.Any() 
      select new { p, attr }; 

如果我正確理解您的模式,應該拉下數據以回答您的問題的兩個部分。