使用Linq获取基于其他系列属性的集合

时间:2016-04-25 12:34:28

标签: c# entity-framework linq

在我正在进行的项目中,我有一个数据库(我无法修改),有两个表(Item和ItemSupplier)。 db中没有外键。在我的EF6中,我创建了两个对象(数据库优先):

<script>

loadTextTrack({videoId:'vTest', // the ID of the video tag
               kind:'subtitles', // the kind of track
               srclang:'en', // the language of the source file (optional)
               targetId:'subtitle'}); // the ID of the element into which to insert the timed text
</script>

我想要的是属于特定供应商的<style type="text/css"> #subtitle{width: 480px; position: absolute; top: 280px;padding: 3px 10px; text-align: center; color:#fff;background-color:#000; font-family: Helvetica,Arial,sans-serif; font-size: 0.9em; font-weight: bold;min-height:3.6em;} </style> 列表。所以我的想法是先获取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列表:

Item

2 个答案:

答案 0 :(得分: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));
    }
}

答案 1 :(得分:0)

  

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

如果您可以使用单个LINQ to Entities查询获得所需结果,为什么要这样做:

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