0

需要帮助将以下查询转换为 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();
}
4

1 回答 1

1

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

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();
于 2013-09-15T15:22:34.777 回答