[英]When is data really retrieved from database using EF Core?
To retrieve data, first I wrote LINQ
query, that I expect not to executed on database until I call the FirstAsync()
method. 为了检索数据,首先我编写了
LINQ
查询,我希望在调用FirstAsync()
方法之前不要在数据库上执行查询。
var query =
from tkn in Db.Set<TableA>()
where tkn.IsActive == true
where tkn.Token == token
select tkn.RelatedObjectMappedToTableB;
var retrievedObject = await clientQuery.FirstAsync();
The problem is while debugging I can see the values of the related object in the Watch
of visual studio, before reaching the call to FirstAsync()
问题是在调试时, 在到达对
FirstAsync()
的调用之前 ,我可以在Visual Studio的Watch
中查看相关对象的值
This means to me that database is already queried and EF has not waited until I ask it to do so. 对我来说,这意味着数据库已经被查询,EF直到我要求它时才等待。
Why is it doing so? 为什么这样做呢? Is my opinion about when a linq query is executed wrong?
我对linq查询何时执行有意见吗?
This means to me that database is already queried and ef has not waited until I ask it to do so.
对我来说,这意味着已经查询了数据库,并且ef直到我要求它时才等待。
No, the database is being queried exactly because you asked it to do so. 不,正在查询数据库正是因为您要求这样做。
Is my opinion about when a linq query is executed wrong?
我对linq查询何时执行有意见吗?
No, it is not, however, 不,不是,
Why is it doing so?
为什么这样做呢?
LINQ retrieves the values in a lazy way, which means that it waits until you perform some enumeration on it. LINQ以惰性方式检索值,这意味着它要等到对它执行一些枚举为止。 Using Visual Studio's Watch Window is asking the query to be evaluated so you can see the actual details.
使用Visual Studio的“监视窗口”要求评估查询,以便您可以查看实际详细信息。
LINQ support two execution behaviors deferred execution and immediate execution. LINQ支持两种执行行为:延迟执行和立即执行。 Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required.
延迟执行意味着将对表达式的求值延迟到实际需要其实现值为止。 It greatly improves performance by avoiding unnecessary execution.
通过避免不必要的执行,它极大地提高了性能。
Deferred execution is applicable to any in-memory collection as well as remote LINQ providers like LINQ-to-SQL, LINQ-to-Entities, LINQ-to-XML, etc. 延迟执行适用于任何内存集合以及远程LINQ提供程序,例如LINQ-to-SQL,LINQ-to-Entities,LINQ-to-XML等。
In the provided example in question, it seems that query executed at where
but that's not happening actually. 在所提供的示例中,查询似乎在
where
执行where
但实际上并没有发生。 The query executed when you call .FirstAsync()
, It means you really need data and C# execute the query, extract data and store data into memory. 当您调用
.FirstAsync()
时执行查询,这意味着您确实需要数据,并且C#执行查询,提取数据并将数据存储到内存中。
If you want immediate execution behavior you can use .ToList()
it will extract the complete projected data and save into memory. 如果要立即执行行为,可以使用
.ToList()
,它将提取完整的投影数据并保存到内存中。
var result =(from tkn in Db.Set<TableA>()
where tkn.IsActive == true
& tkn.Token == token
select tkn.RelatedObjectMappedToTableB).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.