Memory Cache .Net Core Not Persisting Values












0















I have a .NET Core 2.1 application. In Startup.cs configuration method, I use:



services.AddDbContext<ApplicationDbContext>(options =
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
...

services.AddMemoryCache();


Then in my controller:



public class DropDownListController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IMemoryCache _memoryCache;

private const string ProvidersCacheKey = "providers";
private const string AgenciesCacheKey = "agencies";

public DropDownListController(ApplicationDbContext context, IMemoryCache memoryCache )
{
_context = context;
_memoryCache = memoryCache;
}
}


and in the controller also, the method to get the dropdownlist:



public JsonResult GetProvider()
{
IEnumerable<DropDownListCode.NameValueStr> providerlist;

if (_memoryCache.TryGetValue(ProvidersCacheKey, out providerlist))
{
return Json(providerlist);
}
else
{
MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddDays(30);
cacheExpirationOptions.Priority = CacheItemPriority.Normal;

DropDownListCode um = new DropDownListCode(_context);
var result = um.GetProviderList();

_memoryCache.Set(ProvidersCacheKey, result);

return Json(result);
}
}


When I set a breakpoint on the line:



return Json(providerlist);


I see the ProvidersCacheKey is in the _memoryCache, but it has no value.



What happened to the data?



When I do a Quick Watch on _memoryCache, I can see the DbContext object was destroyed. But how can that be, the code works fine but the cache object does not have the data I saved to it.



Any help would be appreciated.










share|improve this question

























  • The first time this hits, it should be falling into the "else" condition, what is the value of "result" after the call to GetProviderList? Can you include the code for GetProviderList(). One quick thing to try, if GetProviderList is returning IQueryable or IEnumerable you might try: var result = up.GetProviderList().ToList(); just to ensure the entities are loaded. IMO though you should avoid caching entities and use POCO data instead. Later calls with different DbContexts will not have these cached entities associated to them if you try using them as references.

    – Steve Py
    Jan 3 at 5:46











  • Excellent: adding ".ToList()" solved the problem. I will make a new entry to mark the question solved. Thank you!

    – Christian Doulos
    Jan 3 at 17:32


















0















I have a .NET Core 2.1 application. In Startup.cs configuration method, I use:



services.AddDbContext<ApplicationDbContext>(options =
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
...

services.AddMemoryCache();


Then in my controller:



public class DropDownListController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IMemoryCache _memoryCache;

private const string ProvidersCacheKey = "providers";
private const string AgenciesCacheKey = "agencies";

public DropDownListController(ApplicationDbContext context, IMemoryCache memoryCache )
{
_context = context;
_memoryCache = memoryCache;
}
}


and in the controller also, the method to get the dropdownlist:



public JsonResult GetProvider()
{
IEnumerable<DropDownListCode.NameValueStr> providerlist;

if (_memoryCache.TryGetValue(ProvidersCacheKey, out providerlist))
{
return Json(providerlist);
}
else
{
MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddDays(30);
cacheExpirationOptions.Priority = CacheItemPriority.Normal;

DropDownListCode um = new DropDownListCode(_context);
var result = um.GetProviderList();

_memoryCache.Set(ProvidersCacheKey, result);

return Json(result);
}
}


When I set a breakpoint on the line:



return Json(providerlist);


I see the ProvidersCacheKey is in the _memoryCache, but it has no value.



What happened to the data?



When I do a Quick Watch on _memoryCache, I can see the DbContext object was destroyed. But how can that be, the code works fine but the cache object does not have the data I saved to it.



Any help would be appreciated.










share|improve this question

























  • The first time this hits, it should be falling into the "else" condition, what is the value of "result" after the call to GetProviderList? Can you include the code for GetProviderList(). One quick thing to try, if GetProviderList is returning IQueryable or IEnumerable you might try: var result = up.GetProviderList().ToList(); just to ensure the entities are loaded. IMO though you should avoid caching entities and use POCO data instead. Later calls with different DbContexts will not have these cached entities associated to them if you try using them as references.

    – Steve Py
    Jan 3 at 5:46











  • Excellent: adding ".ToList()" solved the problem. I will make a new entry to mark the question solved. Thank you!

    – Christian Doulos
    Jan 3 at 17:32
















0












0








0








I have a .NET Core 2.1 application. In Startup.cs configuration method, I use:



services.AddDbContext<ApplicationDbContext>(options =
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
...

services.AddMemoryCache();


Then in my controller:



public class DropDownListController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IMemoryCache _memoryCache;

private const string ProvidersCacheKey = "providers";
private const string AgenciesCacheKey = "agencies";

public DropDownListController(ApplicationDbContext context, IMemoryCache memoryCache )
{
_context = context;
_memoryCache = memoryCache;
}
}


and in the controller also, the method to get the dropdownlist:



public JsonResult GetProvider()
{
IEnumerable<DropDownListCode.NameValueStr> providerlist;

if (_memoryCache.TryGetValue(ProvidersCacheKey, out providerlist))
{
return Json(providerlist);
}
else
{
MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddDays(30);
cacheExpirationOptions.Priority = CacheItemPriority.Normal;

DropDownListCode um = new DropDownListCode(_context);
var result = um.GetProviderList();

_memoryCache.Set(ProvidersCacheKey, result);

return Json(result);
}
}


When I set a breakpoint on the line:



return Json(providerlist);


I see the ProvidersCacheKey is in the _memoryCache, but it has no value.



What happened to the data?



When I do a Quick Watch on _memoryCache, I can see the DbContext object was destroyed. But how can that be, the code works fine but the cache object does not have the data I saved to it.



Any help would be appreciated.










share|improve this question
















I have a .NET Core 2.1 application. In Startup.cs configuration method, I use:



services.AddDbContext<ApplicationDbContext>(options =
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
...

services.AddMemoryCache();


Then in my controller:



public class DropDownListController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IMemoryCache _memoryCache;

private const string ProvidersCacheKey = "providers";
private const string AgenciesCacheKey = "agencies";

public DropDownListController(ApplicationDbContext context, IMemoryCache memoryCache )
{
_context = context;
_memoryCache = memoryCache;
}
}


and in the controller also, the method to get the dropdownlist:



public JsonResult GetProvider()
{
IEnumerable<DropDownListCode.NameValueStr> providerlist;

if (_memoryCache.TryGetValue(ProvidersCacheKey, out providerlist))
{
return Json(providerlist);
}
else
{
MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddDays(30);
cacheExpirationOptions.Priority = CacheItemPriority.Normal;

DropDownListCode um = new DropDownListCode(_context);
var result = um.GetProviderList();

_memoryCache.Set(ProvidersCacheKey, result);

return Json(result);
}
}


When I set a breakpoint on the line:



return Json(providerlist);


I see the ProvidersCacheKey is in the _memoryCache, but it has no value.



What happened to the data?



When I do a Quick Watch on _memoryCache, I can see the DbContext object was destroyed. But how can that be, the code works fine but the cache object does not have the data I saved to it.



Any help would be appreciated.







entity-framework linq-to-sql .net-core memorycache






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 at 18:17









marc_s

583k13011241270




583k13011241270










asked Jan 2 at 17:50









Christian DoulosChristian Doulos

114




114













  • The first time this hits, it should be falling into the "else" condition, what is the value of "result" after the call to GetProviderList? Can you include the code for GetProviderList(). One quick thing to try, if GetProviderList is returning IQueryable or IEnumerable you might try: var result = up.GetProviderList().ToList(); just to ensure the entities are loaded. IMO though you should avoid caching entities and use POCO data instead. Later calls with different DbContexts will not have these cached entities associated to them if you try using them as references.

    – Steve Py
    Jan 3 at 5:46











  • Excellent: adding ".ToList()" solved the problem. I will make a new entry to mark the question solved. Thank you!

    – Christian Doulos
    Jan 3 at 17:32





















  • The first time this hits, it should be falling into the "else" condition, what is the value of "result" after the call to GetProviderList? Can you include the code for GetProviderList(). One quick thing to try, if GetProviderList is returning IQueryable or IEnumerable you might try: var result = up.GetProviderList().ToList(); just to ensure the entities are loaded. IMO though you should avoid caching entities and use POCO data instead. Later calls with different DbContexts will not have these cached entities associated to them if you try using them as references.

    – Steve Py
    Jan 3 at 5:46











  • Excellent: adding ".ToList()" solved the problem. I will make a new entry to mark the question solved. Thank you!

    – Christian Doulos
    Jan 3 at 17:32



















The first time this hits, it should be falling into the "else" condition, what is the value of "result" after the call to GetProviderList? Can you include the code for GetProviderList(). One quick thing to try, if GetProviderList is returning IQueryable or IEnumerable you might try: var result = up.GetProviderList().ToList(); just to ensure the entities are loaded. IMO though you should avoid caching entities and use POCO data instead. Later calls with different DbContexts will not have these cached entities associated to them if you try using them as references.

– Steve Py
Jan 3 at 5:46





The first time this hits, it should be falling into the "else" condition, what is the value of "result" after the call to GetProviderList? Can you include the code for GetProviderList(). One quick thing to try, if GetProviderList is returning IQueryable or IEnumerable you might try: var result = up.GetProviderList().ToList(); just to ensure the entities are loaded. IMO though you should avoid caching entities and use POCO data instead. Later calls with different DbContexts will not have these cached entities associated to them if you try using them as references.

– Steve Py
Jan 3 at 5:46













Excellent: adding ".ToList()" solved the problem. I will make a new entry to mark the question solved. Thank you!

– Christian Doulos
Jan 3 at 17:32







Excellent: adding ".ToList()" solved the problem. I will make a new entry to mark the question solved. Thank you!

– Christian Doulos
Jan 3 at 17:32














1 Answer
1






active

oldest

votes


















0














The method to get providers is:



public IEnumerable<NameValueStr> GetProviderList()
{
var providerlist = (from a in _context.AgencyProvider
where a.Provider == a.AgencyId
select new NameValueStr
{
id = a.Provider,
name = a.Name
});

return providerlist.Distinct();
}


Adding "ToList()" in the calling method worked:



MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
cacheExpirationOptions.Priority = CacheItemPriority.Normal;
DropDownListCode um = new DropDownListCode(_context);
var result = um.GetProviderList().ToList();
_memoryCache.Set(ProvidersCacheKey, result);
return Json(result);


All credit goes to Steve Py… Thank you sir!






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54010918%2fmemory-cache-net-core-not-persisting-values%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    The method to get providers is:



    public IEnumerable<NameValueStr> GetProviderList()
    {
    var providerlist = (from a in _context.AgencyProvider
    where a.Provider == a.AgencyId
    select new NameValueStr
    {
    id = a.Provider,
    name = a.Name
    });

    return providerlist.Distinct();
    }


    Adding "ToList()" in the calling method worked:



    MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
    cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
    cacheExpirationOptions.Priority = CacheItemPriority.Normal;
    DropDownListCode um = new DropDownListCode(_context);
    var result = um.GetProviderList().ToList();
    _memoryCache.Set(ProvidersCacheKey, result);
    return Json(result);


    All credit goes to Steve Py… Thank you sir!






    share|improve this answer




























      0














      The method to get providers is:



      public IEnumerable<NameValueStr> GetProviderList()
      {
      var providerlist = (from a in _context.AgencyProvider
      where a.Provider == a.AgencyId
      select new NameValueStr
      {
      id = a.Provider,
      name = a.Name
      });

      return providerlist.Distinct();
      }


      Adding "ToList()" in the calling method worked:



      MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
      cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
      cacheExpirationOptions.Priority = CacheItemPriority.Normal;
      DropDownListCode um = new DropDownListCode(_context);
      var result = um.GetProviderList().ToList();
      _memoryCache.Set(ProvidersCacheKey, result);
      return Json(result);


      All credit goes to Steve Py… Thank you sir!






      share|improve this answer


























        0












        0








        0







        The method to get providers is:



        public IEnumerable<NameValueStr> GetProviderList()
        {
        var providerlist = (from a in _context.AgencyProvider
        where a.Provider == a.AgencyId
        select new NameValueStr
        {
        id = a.Provider,
        name = a.Name
        });

        return providerlist.Distinct();
        }


        Adding "ToList()" in the calling method worked:



        MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
        cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
        cacheExpirationOptions.Priority = CacheItemPriority.Normal;
        DropDownListCode um = new DropDownListCode(_context);
        var result = um.GetProviderList().ToList();
        _memoryCache.Set(ProvidersCacheKey, result);
        return Json(result);


        All credit goes to Steve Py… Thank you sir!






        share|improve this answer













        The method to get providers is:



        public IEnumerable<NameValueStr> GetProviderList()
        {
        var providerlist = (from a in _context.AgencyProvider
        where a.Provider == a.AgencyId
        select new NameValueStr
        {
        id = a.Provider,
        name = a.Name
        });

        return providerlist.Distinct();
        }


        Adding "ToList()" in the calling method worked:



        MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
        cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
        cacheExpirationOptions.Priority = CacheItemPriority.Normal;
        DropDownListCode um = new DropDownListCode(_context);
        var result = um.GetProviderList().ToList();
        _memoryCache.Set(ProvidersCacheKey, result);
        return Json(result);


        All credit goes to Steve Py… Thank you sir!







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 3 at 17:37









        Christian DoulosChristian Doulos

        114




        114
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54010918%2fmemory-cache-net-core-not-persisting-values%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

            How to fix TextFormField cause rebuild widget in Flutter