簡體   English   中英

使用Linq獲取基於其他系列屬性的集合

[英]Get a collection based on the property of an other collection with Linq

在我正在研究的項目中,我有一個數據庫(我無法修改)有兩個表(Item和ItemSupplier)。 db中沒有外鍵。 在我的EF6中,我創建了兩個對象(數據庫優先):

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));
    }
}

請嘗試以下方法:

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));
    }
}

所以我的想法是先獲取ItemSupplier列表,然后使用Any()獲取Item列表

如果您可以使用單個LINQ to Entities查詢獲得所需結果,為什么要這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM