2016-04-25 146 views
1

在我正在開發的項目中,我有一個數據庫(我無法修改)使用兩個表(Item和ItemSupplier)。 db中沒有外鍵。在我的EF6我已經創建了兩個對象(數據庫在前):獲取基於Linq的其他集合的屬性的集合

public class Item { 
    public string ItemCode { get; set;} 
    public string Description { get; set; } 
    public double SalesPrice { get; set; } 
} 

public class ItemSupplier { 
    public string ItemCode { get; set; } 
    public string AccountCode { get; set; } 
} 

我想是屬於特定供應商的Item列表。所以我的想法是首先得到的ItemSupplier列表,然後開始使用Any()Item列表:

public List<Item> GetItemsByAccountCode(string code) 
{ 
    List<Item> itemList = new List<Item>(); 
    using(DbEntities context = new DbEntities()) 
    { 
     // Get the list of items of a specific supplier 
     List<ItemSupplier> itemSupList = context.ItemSupplier.Where(p => 
              p.AccountCode == code).ToList(); 

     // Get al the items based on the itemSupList 
     // Below is not working 
     itemList = context.Item.Where(p => itemSupList.Any(x => x.ItemCode)); 
    } 
} 

回答

0

所以我的想法是第一獲取列表物品供應商,然後使用任何()獲得物品清單()

爲什麼woul d你想這樣做,如果你可以通過單個LINQ to Entities查詢得到期望的結果,像這樣:

itemList = context.Items.Where(item => db.ItemSupplier.Any(supplier => 
    supplier.ItemCode == item.ItemCode && supplier.AccountCode == code)) 
    .ToList(); 
0

嘗試以下操作:

public List<Item> GetItemsByAccountCode(string code) 
{ 
    List<Item> itemList = new List<Item>(); 
    using(DbEntities context = new DbEntities()) 
    { 
     // Get the list of items codes of a specific supplier 
     var itemCodes = context.ItemSupplier 
           .Where(p => p.AccountCode == code) 
           .Select(p => p.ItemCode) 
           .ToList(); 

     // Get al the items based on the itemSupList 
     // Below is not working 
     itemList = context.Item.Where(p => itemCodes.Contains(p.ItemCode)); 
    } 
} 
相關問題