【问题标题】:LINQ lambda for many to many relationship多对多关系的 LINQ lambda
【发布时间】:2016-04-11 12:15:10
【问题描述】:

Products 和 CategoryGroups 之间存在多对多的数据关系,我正在选择也在特定 CategoryGroups 中的所有产品(从 productList 的起点)(CategoryGroup Id 的列表在 groupIds 中给出) .

这可以使用以下 LINQ 表达式成功实现:

productList =
    from p in productList
    where (
    from g in p.CategoryGroup
    where groupIds.Contains(g.CategoryGroupId)
    select g
    ).Any()
    select p;

地点:

var productList = db.Products
    .Where(a => a.ThisCondition == thisCondition)
    .ToList();  

var groupIds = db.CategoryGroups
    .Where(a => a.ThatCondition == thatCondition)
    .Select(a => a.CategoryGroupId)
    .ToList();

是否可以用一个 LINQ lambda 表达式替换 productList LINQ 表达式?

非常感谢任何帮助。

【问题讨论】:

    标签: asp.net asp.net-mvc linq linq-to-sql


    【解决方案1】:

    如果您使用两个集合导航属性(如tutorial)表示您的多对多关系,您可以将查询简化为:

    var productList = db.Products
                        .Where(a => a.ThisCondition == thisCondition 
                                    && a.CategoryGroups.Count(c=>groupIds.Contains(c.CategoryGroupId))>0);
    

    或者你也可以使用Any扩展方法:

    var productList = db.Products
                        .Where(a => a.ThisCondition == thisCondition 
                                    && a.CategoryGroups.Any(c=>groupIds.Contains(c.CategoryGroupId)));
    

    【讨论】:

    • 这太棒了,谢谢 - 两者都有效。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多