动态linq multiple vs single .where查询

时间:2016-08-23 09:53:05

标签: c# linq dynamic-linq

为什么查询提供的单个结果与查询的多个结果不同?

query.Where("666 = ID");
query.Where("ActiveFrom < @0 && ActiveTo > @1 && ValidFrom < DateTime.Now && ValidTo > DateTime.Now", toDate, fromDate);

query.ToString();导致:

SELECT  *
    FROM [Country] AS [Extent1]
    WHERE 666 = [Extent1].[ID]

和多个调用

的查询相同
query = query.Where("ActiveFrom < @0", toDate);
query = query.Where("ActiveTo > @0", fromDate);
query = query.Where("ValidFrom < DateTime.Now");
query = query.Where("ValidTo > DateTime.Now");

结果:

SELECT  *
FROM [Country] AS [Extent1]
WHERE (666 = [Extent1].[ID]) AND 
([Extent1].[ActiveFrom] < convert(datetime2, '2016-10-23 11:40:35.9538054', 121)) AND 
([Extent1].[ActiveTo] > convert(datetime2, '2016-06-23 11:40:35.9518052', 121)) AND
([Extent1].[ValidFrom] < (SysDateTime())) AND 
([Extent1].[ValidTo] > (SysDateTime()))

2 个答案:

答案 0 :(得分:2)

要使不同的Where相关,您需要将它们分配回query

//instead of:
query.Where("666 = ID");
query.Where("ActiveFrom < @0 && ActiveTo > @1 && ValidFrom < DateTime.Now && ValidTo > DateTime.Now", toDate, fromDate);

//do:
query = query.Where("666 = ID");
query = query.Where("ActiveFrom < @0 && ActiveTo > @1 && ValidFrom < DateTime.Now && ValidTo > DateTime.Now", toDate, fromDate);

此外,Where来电也可以链接。大多数linq扩展方法返回IEnumerable<TSource>,因此可以链接。

在第二个查询中应用链接,它将如下所示:

query = query.Where("ActiveFrom < @0", toDate)
             .Where("ActiveTo > @0", fromDate)
             .Where("ValidFrom < DateTime.Now")
             .Where("ValidTo > DateTime.Now");

答案 1 :(得分:1)

因为调用不修改查询,所以它们返回表示修改后的查询的新实例。因此,第二个示例导致大查询,而第一个示例仅产生一个简单的where条件。