开发者

Do Linq to Entities queries *always* hit the database?

开发者 https://www.devze.com 2023-01-19 07:33 出处:网络
My understanding of the Entity Framework is that if it can answer a query from its cache, it will.My simple testing, however, shows repeated queries hit the database even though开发者_StackOverflow社区

My understanding of the Entity Framework is that if it can answer a query from its cache, it will. My simple testing, however, shows repeated queries hit the database even though开发者_StackOverflow社区 they were previously answered positively:

var u1 = context.Users.SingleOrDefault(u => u.Id == 1);
var u2 = context.Users.SingleOrDefault(u => u.Id == 1);

These queries are successful. For each, I see a SELECT TOP (2) in SQL Profiler.

Why does EF go to the database for that second query?


EF always executes query but returns the same instance of the object. Second query is not materialized into the new object instead instance created by the first query is returned. Here is the article about that behavior. There are some aditional concepts which can force second query for example to update existing instance.


Well, because EF doesn't use caching. nHibernate does. Here article on how to enable caching with EF.

Edit: EF doesn't have transparent out-of-the-box cache. But it has explicit cache within unit of work: ObjectContext.GetObjectByKey

0

精彩评论

暂无评论...
验证码 换一张
取 消