2014-09-03 49 views
1

我初學者與EF,所以我的問題可能是基本的,但我找不到任何答案...導航橫跨關係,EF

我有一個SQL數據庫結構緊湊,從中我產生的實體模型通過VS嚮導。一切似乎都很好,我用良好的映射檢索了我所有的關係。

所以當我從這裏瞭解:http://msdn.microsoft.com/en-us/library/bb386932(v=vs.110).aspx我應該能夠做到這一點,「跨關係查詢」:

IQueryable<Ingredient> IngQuery = from i in db.Ingredient 
      where i.Product.ID == ProdID 
      select i; 

,但我得到了以下錯誤:

'System.Collections.Generic.ICollection' does not contain a definition for 'ID' and no extension method 'ID' accepting a first argument of type 'System.Collections.Generic.ICollection' could be found (are you missing a using directive or an assembly reference?).

This error occurs when you try to call a method or access a class member that does not exist

但是,如果我深入到自動生成的代碼中,我可以看到公共屬性'ID'被聲明爲'產品','成分'返回'產品'的集合:

  • 成分

    public partial class Ingredient 
    { 
        public Ingredient() 
        { 
         this.Product = new HashSet<Product>(); 
        } 
    
        public string Name { get; set; } 
        public int ID { get; set; } 
    
        public virtual ICollection<Product> Product { get; set; } 
    } 
    
  • 產品

    public partial class Products 
    { 
        public Products() 
        { 
         this.Ingredient = new HashSet<T_PROPSTHERAP>(); 
        } 
        public int ID { get; set; } 
        public string Name { get; set; } 
        public string Usage { get; set; } 
        public byte[] Photo { get; set; } 
        public int FK_OrganeProduct { get; set; } 
        public int FK_Type { get; set; } 
        public virtual OrganeProduct OrganeProduct { get; set; } 
        public virtual Type Type { get; set; } 
        public virtual ICollection<Ingredient> Ingredient { get; set; } 
    } 
    

但正如我預期這是行不通的。

我可以使用下面的解決方法:

List<Ingredient> lstIng = (_oTest.Products 
        .Where(p => p.Name == (string)lsbProducts.SelectedItem) 
        .SelectMany(p => p.T_PROPSTHERAP)).ToList(); 

但我不認爲這是應該做的伎倆一個聰明的辦法......我不明白,我缺少的是什麼?

任何人都可以幫忙嗎?

回答

3

如果我理解正確,您正在嘗試根據產品ID找到成分。正如您所知道的,Product屬性是一個集合,而不是一個單一的對象。

您需要的是根據產品ID過濾產品,您可以使用Any來過濾收集。

IQueryable<Ingredient> IngQuery = from i in db.Ingredient 
      where i.Product.Any(p => p.ID == ProdID) 
      select i; 

這意味着:

Looking for Ingredient if any of its product has ID equals to ProdID.

您還可以使用All,如果你正在尋找的是:

Looking for Ingredient if all of its products have ID equals to ProdID.

IQueryable<Ingredient> IngQuery = from i in db.Ingredient 
      where i.Product.All(p => p.ID == ProdID) 
      select i; 

PS

但是,根據您的解決方法,使用任何是您正在尋找的。

+0

M.Any謝謝! :)這正是我的預期! – Levenbrech 2014-09-03 15:21:58

+0

@Levenbrech,不客氣,不要忘記[標記爲答案](http://meta.stackexchange.com/a/5235)如果有幫助 – 2014-09-03 15:26:27