DbContext caching

前端 未结 2 876
闹比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.

提交回复
热议问题