DbContext caching

前端 未结 2 877
闹比i
闹比i 2021-01-07 07:26

I know the caching of DbContext is not good idea. But I would like to do it fine. What do you think about this way?

public class Context : DbContext
{
    pr         


        
相关标签:
2条回答
  • 2021-01-07 07:52

    The DbContext is a cache. Keeping hold of it for a long time is a terrible idea... it will slowly consume your application's memory hanging on to data that may well be stale.

    It was not designed to be used in the way you propose.

    Don't do it.

    A DbContext is a transient object that should be used and disposed of in the smallest scope possible.

     using(var ctx = new MyDbContext())
     {
          //make some changes
          ctx.SaveChanges();
     }
    

    That's how it was designed to be used. Use it properly.

    0 讨论(0)
  • 2021-01-07 07:53

    This is an XY problem. Why do you want to "cache" the DbContext? What benefit do you think you'll gain from this?

    You should not do this, ever. The class was not meant for this. It will instead cause performance problems (undoing the benefit you think to gain) and persistent errors after you attached invalid entities - you'll never be able to save entities using this context again, as the change tracker holds the entities.

    See Correct usage of EF's DBContext in ASP.NET MVC application with Castle Windsor, Working with DbContext, Managing DbContext the right way with Entity Framework 6: an in-depth guide, Manage the lifetime of dbContext or any of the other thousands of hits on searching the web for "entity framework dbcontext lifetime".

    If you want to cache data, then instead cache the records themselves. There are existing solutions (code and libraries) that can help you with this, which is called "second level caching". No need to write it yourself. See for example How to make Entity Framework cache some objects.

    0 讨论(0)
提交回复
热议问题