如何针对 linq to 实体中的联接表创建多个嵌套条件

本文关键字:创建 条件 嵌套 何针 linq to 实体 | 更新日期: 2023-09-27 18:31:25

需要帮助将以下查询转换为 Linq to Entities。

select * from tableA a join 
tableB b on a.ProductId = b.ProductId and a.UserId = b.UserId
where a.ProductId = 60244
and ((b.Column1 = 33 and b.Column2 >= 3) or (b.Column1 = 24 and b.Column2 >= 2))

我从这个表达式开始,但我不知道如何根据列表为 tableB 创建复杂条件。我试图遵循谓词生成器的模式,但我遇到了障碍,因为这些示例不处理连接的表。

public IList<tableA> GetSomeStuff(int productId, List<tableB> filters)
{
    var query = from a in tableA
        join b in tableB
        on new
        {
            ProductId = a.ProductId,
            UserId = a.UserId
        }
        equals
        new
        {
            ProductId = b.ProductId,
            UserId = b.UserId
        }
        where a.ProductId == 6544
        select a;

    var tableBPredicate = PredicateBuilder.True<tableB>();
    foreach (var filter in filters)
    {
        /* build up tableB conditions here */
        tableBPredicate = tableBPredicate.And(p => p.Column1 == filter.Column1);
        tableBPredicate = tableBPredicate.And(p => p.Column2 => filter.Column2);
    }
    // this won't compile because query is of type tableA and not tableB
    return query.AsExpandable().Where(tableBPredicate).ToList();
}

如何针对 linq to 实体中的联接表创建多个嵌套条件

如果您先应用谓词,然后将过滤集连接到另一个表,它应该可以工作:

var tableBPredicate = PredicateBuilder.True<tableB>();
foreach (var filter in filters)
{
    /* build up tableB conditions here */
    tableBPredicate = tableBPredicate.And(p => p.Column1 == filter.Column1);
    tableBPredicate = tableBPredicate.And(p => p.Column2 => filter.Column2);
}
var tableBQuery = tableB.AsExpandable().Where(tableBPredicate);
var query = from b in tableBQuery
    join a in tableA
    on new
    {
        ProductId = b.ProductId,
        UserId = b.UserId
    }
    equals
    new
    {
        ProductId = a.ProductId,
        UserId = a.UserId
    }
    where a.ProductId == 6544
    select a;
return query.ToList();