VahidN / EFSecondLevelCache.Core

Entity Framework Core Second Level Caching Library
Apache License 2.0
326 stars 50 forks source link

Where() statements never resolve from cache #25

Closed ZenSoftware closed 5 years ago

ZenSoftware commented 5 years ago

Summary of the issue

I noticed that EFCore Where() statements never get pulled from the cache. Is this intentional? When I change the query to be a First() statement, it will pull from the cache just fine. I simply copy and pasted the install instructions to register the services for EFSecondLevelCache.Core. Do let me know if you need any other information.

Environment

EFSecondLevelCache.Core v1.6.4
Asp.Net Core 2.2
Windows 10
Visual Studio 2017

Example code/Steps to reproduce:

using System.Linq;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using EFSecondLevelCache.Core;
using My.Models;

namespace My.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BlogCommentsController : ControllerBase
    {
        private readonly MyContext _context;

        public BlogCommentsController(MyContext context)
        {
            _context = context;
        }

        [HttpGet("{id}")]
        public ActionResult<List<BlogComment>> GetBlogComment(int id)
        {
        // This is expected to resolve from the cache, but it always queries the database
            var blogComment = _context.BlogComments.Cacheable().Where(x => x.BlogId == id).ToList();

            // This does pull from the cache
            var singleComment = _context.BlogComments.Cacheable().First(x => x.BlogId == id);

            return blogComment;
        }
    }
}

Output:

When tracing transactions for my MS-SQL database, I see the following query produced every time I hit the GetBlogComment(int id) action above.

[SELECT [x].[Id], [x].[AuthorUserId], [x].[BlogId], [x].[Content]
FROM [BlogComments] AS [x]
WHERE [x].[BlogId] = @__context_Source_Id_0](url)

Again, when changing it to First() I do not see my database getting hit, implying that it pulled from the cache.

VahidN commented 5 years ago

You should put the Cacheable() before the materialization part or ToList() here (it should be able to calculate the final SQL of the LINQ statement).

var blogComments = _context.BlogComments.Where(x => x.BlogId == id).Cacheable().ToList();
ZenSoftware commented 5 years ago

Ah! Yes that fixed it. Thanks for this wonderful library. It's very straight forward to use. ^_^

You can go ahead and close this issue.

lock[bot] commented 4 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related problems.