EntitiFramework 6不追查linq查询结果

时间:2018-08-21 08:47:06

标签: entity-framework entity-framework-6 linq-to-entities

作为测试,我设置了一个控制器动作,该动作在同一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不缓存查询结果,如何使它缓存?

0 个答案:

没有答案