作为测试,我设置了一个控制器动作,该动作在同一DbContext
中执行1次查询两次,以查看查询是否被阻塞。
private TestWebAppContext db = new TestWebAppContext();
public void Log(string text)
{
Debug.Write(text);
}
// GET: api/Posts
public ICollection<Post> GetPosts()
{
db.Database.Log = this.Log;
var posts = db.Posts.Where(p => p.Id < 10).ToList();
var otherPosts = db.Posts.Where(p => p.Id < 10).ToList();
return otherPosts;
}
但是,在运行此代码时,在我的“调试输出”窗口中,我可以清楚地看到查询被执行了两次:
Opened connection at 21-Aug-18 10:44:26 AM +02:00
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Title] AS [Title],
[Extent1].[Content] AS [Content]
FROM [dbo].[Posts] AS [Extent1]
WHERE [Extent1].[Id] < 10
-- Executing at 21-Aug-18 10:44:26 AM +02:00
-- Completed in 14 ms with result: SqlDataReader
Closed connection at 21-Aug-18 10:44:26 AM +02:00
Opened connection at 21-Aug-18 10:44:26 AM +02:00
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Title] AS [Title],
[Extent1].[Content] AS [Content]
FROM [dbo].[Posts] AS [Extent1]
WHERE [Extent1].[Id] < 10
-- Executing at 21-Aug-18 10:44:26 AM +02:00
-- Completed in 13 ms with result: SqlDataReader
Closed connection at 21-Aug-18 10:44:26 AM +02:00
即使使用Load
方法(我认为该方法专门缓存查询),查询也会多次执行:
public ICollection<Post> GetPosts()
{
db.Database.Log = this.Log;
db.Posts.Where(p => p.Id < 10).Load();
var posts = db.Posts.Where(p => p.Id < 10).ToList();
var otherPosts = db.Posts.Where(p => p.Id < 10).ToList();
return otherPosts;
}
结果至:
Opened connection at 21-Aug-18 10:42:25 AM +02:00
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Title] AS [Title],
[Extent1].[Content] AS [Content]
FROM [dbo].[Posts] AS [Extent1]
WHERE [Extent1].[Id] < 10
-- Executing at 21-Aug-18 10:42:25 AM +02:00
-- Completed in 17 ms with result: SqlDataReader
Closed connection at 21-Aug-18 10:42:25 AM +02:00
Opened connection at 21-Aug-18 10:42:28 AM +02:00
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Title] AS [Title],
[Extent1].[Content] AS [Content]
FROM [dbo].[Posts] AS [Extent1]
WHERE [Extent1].[Id] < 10
-- Executing at 21-Aug-18 10:42:28 AM +02:00
-- Completed in 31 ms with result: SqlDataReader
Closed connection at 21-Aug-18 10:42:28 AM +02:00
Opened connection at 21-Aug-18 10:42:29 AM +02:00
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Title] AS [Title],
[Extent1].[Content] AS [Content]
FROM [dbo].[Posts] AS [Extent1]
WHERE [Extent1].[Id] < 10
-- Executing at 21-Aug-18 10:42:29 AM +02:00
-- Completed in 12 ms with result: SqlDataReader
Closed connection at 21-Aug-18 10:42:29 AM +02:00
为什么DbContext
不缓存查询结果,如何使它缓存?