How to pass DbContext (EntityFramework SqlConnection) to another Method?

c# entity-framework entity-framework-6 sqlite


Problem providing DbContext to another method, for instance:

public bool MarkCustomerForDelete(Customer customerObj)
        using(var dbContext = new MyContext())
            using(var dbTransaction = dbContext.Database.BeginTransaction())

                //Clear all orders for the Given Customers          
                var orderList = dbContext.Orders.Where(x=> == customerObj.OrderId).ToList();

                CommonLogicMethod(dbContext, orderList);

                customerObj.Status = "Deleted";
// The Modification will fail over due to the Customer Object for that object is already attached to the DbContext with Previous Values
                dbContext.Entry(customerObj).State = EntityState.Modified;

                return true;
public void DeleteOrderRelatedData(MyContext dbContext, List<Orders> orderList)
    foreach(var entity2 in entity2List)
        var OrderAddresses = dbContext.OrderAddresses.Where(x=>x.Id == entity2.Id).ToList();
        //Now if here the dbContext has 100 Entities (Tables)
        //It internally Enumerates all the entities in the Local cache i.e. dbContext.Coupons.Local has all the Records from the DB in the Local present.


Why does the internal call to all the data in the dbContext happen when DbContext is handed to another method. Customers. All of the database's data is available locally in first-level cache?

How may DbContext be passed from one method to another without causing the previously mentioned problem?

This is causing a problem with data modification, causing DeleteCustomer to fail. Now, if the DeleteOrderRelatedData method's code is combined into the DeleteCustomer function, everything runs smoothly.

I added a Logs for the dbContext, and when the Function receives it, dbContext internally calls all the Select queries associated with the various Queries.

Please watch this video for more information: Link

Applied instruments:

  1. 6.0 Entity Framework
  2. System.Data.Sqlite
  3. For MethodBoundary Aspect, use PostSharp.
3/17/2016 3:45:34 PM

Accepted Answer

I was using PostSharp to log the traces while using OnMethodBoundaryAspect to cause the problem. This was now internally using arguments. Since the arguments were serialized during logging, this was the problem.

3/17/2016 4:05:57 PM

Popular Answer


Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow