传递选择查询引用Linq查询中的两个连接记录

时间:2018-05-02 10:25:24

标签: c# linq-to-sql

假设我有一个名为CustomerTransaction的表,我可以将选择标准传递给例如

的例程
void GetData1(Expression<Func<CustomerTransaction, bool>> selection)
{
    CustomerTransaction.Where(selection).Take(2).Dump();
}

使用

之类的代码
Expression<Func<CustomerTransaction, bool>> query = r => (r.CustomerID == 1);
GetData1(query);

但是,我希望能够从这个表中加入两个记录,并传入一个参考这两个表的选择标准。

例如,以下内容将编译(在LinqPad中),

void GetData2(Expression<Func<Tuple<CustomerTransaction,CustomerTransaction>, bool>> selection)
{
   var baseQuery = (from ct1 in CustomerTransaction 
        join ct2 in CustomerTransaction on ct1.MasterTransactionID equals ct2.RelatedTransactionID 
        select new Tuple<CustomerTransaction, CustomerTransaction> ( ct1, ct2)) ;

    var query = baseQuery.Where(selection).Dump();
}

Expression<Func<Tuple<CustomerTransaction,CustomerTransaction>, bool>> query2 =
       r => r.Item1.CustomerID != r.Item2.CustomerID;

GetData2(query2);

但是,它不会运行,因为SQL不处理元组。

如果我试图用SQL会理解的某种方式写这个,那么我就不能通过选择标准,因为我不知道选择的类型

例如

void GetData3( ???  selection)
{
    var baseQuery = (from ct1 in CustomerTransaction
     join ct2 in CustomerTransaction on ct1.MasterTransactionID equals ct2.RelatedTransactionID
     select new { Customer1 = ct1.CustomerID, Customer2 = ct2.CustomerID }  );

    baseQuery.Where(selection).Dump();
}

显然,真正的查询更复杂,它们是多个选择标准,我试图避免为每个可能的部分标准重复查询。

有什么方法吗?

1 个答案:

答案 0 :(得分:1)

您可以创建一个代表join结果的显式类,并在该类上创建Where表达式:

public class CT2 {
    public CustomerTransaction ct1;
    public CustomerTransaction ct2;
}

然后,您可以在查询和Where表达式中使用该类:

void GetData2(Expression<Func<CT2, bool>> selection) {
    var baseQuery = from ct1 in db.CustomerTransaction
                    join ct2 in db.CustomerTransaction on ct1.MasterTransactionID equals ct2.RelatedTransactionID
                    select new CT2 { ct1 = ct1, ct2 = ct2 };

    var query = baseQuery.Where(selection).Dump();
}

Expression<Func<CT2, bool>> query2 =
       r => r.ct1.CustomerID != r.ct2.CustomerID;

GetData2(query2);