编译后的查询每次都返回相同的内容
我有这个已编译的查询:
private static Func<DBContext, Foo> FooQuery = CompiledQuery.Compile<DBContext, Foo>(
_db => _db.FooTable.SingleOrDefault(f => f.DeletionDate == null || f.DeletionDate > DateTime.UtcNow)
);
当我运行它一次时,它返回预期的 Foo 对象。
但是,即使在数据库中设置了该对象的 DeletionDate 之后,它仍然返回相同的对象 - 我期待 null。 (在回收应用程序池后,它按预期返回 null。)
出于某种原因,当我使用以下编译查询(并传入 DateTime.UtcNow)时,它会起作用,但我不确定为什么。
private static Func<DBContext, DateTime, Foo> FooQuery = CompiledQuery.Compile<DBContext, DateTime, Foo>(
(_db, now) => _db.FooTable.SingleOrDefault(f => f.DeletionDate == null || f.DeletionDate > now)
);
I have this compiled query:
private static Func<DBContext, Foo> FooQuery = CompiledQuery.Compile<DBContext, Foo>(
_db => _db.FooTable.SingleOrDefault(f => f.DeletionDate == null || f.DeletionDate > DateTime.UtcNow)
);
When I run it once, it returns the expected Foo object.
But then, even after that object's DeletionDate is set in the db, it still returns the same object -- I am expecting null. (It returns null, as expected, after recycling the app pool.)
For some reason, it works when I use the following compiled query instead (and pass in DateTime.UtcNow), but I'm not sure why.
private static Func<DBContext, DateTime, Foo> FooQuery = CompiledQuery.Compile<DBContext, DateTime, Foo>(
(_db, now) => _db.FooTable.SingleOrDefault(f => f.DeletionDate == null || f.DeletionDate > now)
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您在编译的查询中传入 DateTime.UtcNow 时,您将设置一个常量日期作为 SQL 的一部分。但是,当您传入参数时,您正在创建一个参数化查询,其中参数(即日期)可以在每次调用时更改。
当您回收应用程序池时,您将再次重新编译查询。
查看生成的 SQL,您就会明白我在说什么。
When you pass in DateTime.UtcNow in the compiled query, you are setting a constant date as part of the SQL. But when you pass in a parameter, you are creating a parameterized query in which the parameter (i.e. the date) can change each time you call it.
When you recycle the App Pool, you're recompiling the query all over again.
Check out the generated SQL and you'll see what I'm talking about.