gpt4 book ai didi

linq to sql多个Where()语句不创建单个表达式

转载 作者:行者123 更新时间:2023-12-01 09:24:39 25 4
gpt4 key购买 nike

我的理解是下面的代码:

IQueryable<Things> things = dataContext.Things.Take(10);
if (fromDate > new DateTime(1980, 1, 1))
things = things.Where(a => a.InsertedDate > fromDate);
if (toDate < defaultDate)
things = things.Where(a => a.InsertedDate < toDate);

应该产生一个查询(假设日期通过条件),例如:

select top 10 [fields] from things
where inserteddate > '1/8/2010'
and inserteddate < '1/12/2010'

我已经单步执行并确认两个Where() 语句已设置,但是当我调用things.ToList() 时,我收到查询:

select top 10 [fields] from things

为什么这两个地方没有合并到实际查询中运行?

最佳答案

你的代码是错误的。调用Queryable.Take应该在末尾以获得您想要的查询:

IQueryable<Things> things = dataContext.Things;

if (fromDate > new DateTime(1980, 1, 1))
{
things = things.Where(a => a.InsertedDate > fromDate);
}

if (toDate < defaultDate)
{
things = things.Where(a => a.InsertedDate < toDate);
}

things = things.Take(10);

当您首先调用 Take 时,它会从整个数据库中查找前十个元素,然后仅评估这 10 个项目的Where 原因。结果通常包含少于十个元素。

理论上,您的错误代码可以作为单个数据库查询运行:

SELECT [fields]
FROM
(
SELECT TOP 10 [fields] FROM table1
) T1
WHERE inserteddate > '2010-01-08'
AND inserteddate < '2010-01-12'

看来这个优化还没有实现。但我怀疑这样的查询是否经常使用。

关于linq to sql多个Where()语句不创建单个表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4587379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com