EF6 - Is there a way to clear the EF cache / local elements without making any changes to the database?

Basically, I mix EF with a single call to a stored procedure that does some batch deletion, otherwise EF is too slow.

Here is some kind of pseudo-code for this scenario (in reality I have more complex code):

public void RemoveCustomer(int customerUID)
{
   // this code is running in one db transaction
   {
      // retrieve certain orders of particular customer using EF
      var orders = repoOrders.GetOrdersOfCustomer(filter, customerUID);

      // do something with above orders before deletion using EF
      repoX.DoSomethingWithOrders(orders);

      // call SP to delete all orders of customer 
      repoOrders.DeleteAllOrdersOfCustomer(customerUID);  // this calls a stored procedure

      // delete customer using EF 
      repoCustomers.DeleteCustomer(customerUID);  // throws exception due to relationship!
   }
}

Of course, customer orders are a ratio one-to-many(1: m).

I want to avoid the exception in the above scenario that occurs when some orders loaded by the context belonging to the client are deleted. The exception is:

" , NULL. , . , , ."

, , / <DbSet>.Local - , .

, Detach , , .

?

: EF, EF , ADO.NET, , BL ... .

. .

+4
4

, .., TransactionScope, , .

void DeleteAllOrdersOfCustomer(Guid customerUID)
{
    using (var context = new Context())
    {
       ...
       context.SaveChanges();
    }
}

...

using (var ts = new TransactionScope())
{
   // call SP to delete all orders of customer 
   repoOrders.DeleteAllOrdersOfCustomer(customerUID);  // this calls a stored procedure

   // delete customer using EF 
   repoCustomers.DeleteCustomer(customerUID);  // throws exception due to relationship!
   ts.Complete();
}
+6

, , . RefreshMode Enum, , StoreWins.

, EF, , .

0

SqlQuery dbset , :

context.xdbset.SqlQuery("storedprocedure; select * from xdbset");  

, select *..., , , "xdbset".

You can look here for such discussions.

0
source

One way to have batch deletion is to set the DELETE ON CASCADE to foreign keys. You need WillCascadeOnDeleteto configure the model. You can try this instead of using a stored procedure:

var customer = context.Customers.Include(c => c.Orders).Where(c => c.CustomerId == someId).ToList();
foreach(var order in customer.Orders)
{
    context.Entry(order).State = EntityState.Deleted;
}
context.Entry(customer).State = EntityState.Deleted;
context.SaveChanges();
-1
source

Source: https://habr.com/ru/post/1543579/


All Articles