2016-04-25 145 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)); 
    } 
} 
相关问题