Nested DbContext due to method calls - Entity Framework

后端 未结 4 1717
广开言路
广开言路 2020-12-13 04:21

In the following case where two DbContexts are nested due to method calls:

public void Method_A() {
    using (var db = new SomeDbContext()) {
        //...d         


        
4条回答
  •  半阙折子戏
    2020-12-13 04:45

    It is a bit late answer, but still people may be looking so here is another way.

    Create class, that cares about disposing for you. In some scenarios, there would be a function usable from different places in solution. This way you avoid creating multiple instances of DbContext and you can use nested calls as many as you like.

    Pasting simple example.

    public class SomeContext : SomeDbContext
    {
        protected int UsingCount = 0;
        public static SomeContext GetContext(SomeContext context)
        {
            if (context != null)
            {
                context.UsingCount++;
            }
            else
            {
                context = new SomeContext();
            }
            return context;
        }
    
        private SomeContext()
        {
        }
    
        protected bool MyDisposing = true;
        protected override void Dispose(bool disposing)
        {
            if (UsingCount == 0)
            {
                base.Dispose(MyDisposing);
                MyDisposing = false;
            }
            else
            {
                UsingCount--;
            }
        }
    
        public override int SaveChanges()
        {
            if (UsingCount == 0)
            {
                return base.SaveChanges();
            }
            else
            {
                return 0;
            }
        }
    }
    

    Example of usage

    public class ExmapleNesting
    {
        public void MethodA()
        {
            using (var context = SomeContext.GetContext(null))
            {
                // manipulate, save it, just do not call Dispose on context in using
                MethodB(context);
            }
    
            MethodB();
        }
    
        public void MethodB(SomeContext someContext = null)
        {
            using (var context = SomeContext.GetContext(someContext))
            {
                // manipulate, save it, just do not call Dispose on context in using
                // Even more nested functions if you'd like
            }
        }
    }
    

    Simple and easy to use.

提交回复
热议问题