C#-动态Linq Multiple vs Single .where查询
作者:互联网
为什么单个where查询给出的结果与多个where查询给出的结果不同?
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]
和具有多个where调用的相同查询
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()))
解决方法:
为了使不同的位置相关,您需要将它们分配回查询:
//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);
另外,可以将“哪里”电话链接起来.大多数linq扩展方法返回IEnumerable< TSource>.因此可以被链接.
将链接应用于第二个查询,它将看起来像这样:
query = query.Where("ActiveFrom < @0", toDate)
.Where("ActiveTo > @0", fromDate)
.Where("ValidFrom < DateTime.Now")
.Where("ValidTo > DateTime.Now");
标签:dynamic-linq,linq,c 来源: https://codeday.me/bug/20191118/2026828.html