I have a structure of cart that contains orders that contains order items that contains order sub items. All this structure also work with logical delete. I have on each level a data delete property. I use Entity Framework 6.2.4
So I have C-O-OI-OSI
Here is my code to get my cart with all the structure:
var cart = Context.Cart
.AsNoTracking()
.Include(y => y.Orders.Select(z => z.OrderItems.Select(x => x.OrderSubItems)))
.SingleOrDefault(y => y.Code == cartCode);
Then to remove all my deleted element I do this loop:
foreach (var order in cart.Orders)
{
if (order.DateDelete != null)
{
Context.Entry(order).State = EntityState.Detached;
cart.Orders.Remove(order);
}
else
{
foreach (var orderItem in order.OrderItems)
{
if (orderItem.DateDelete != null)
{
Context.Entry(orderItem).State = EntityState.Detached;
order.OrderItems.Remove(orderItem);
}
else
{
foreach (var orderSubItem in orderItem.OrderSubItems)
{
if (orderSubItem.DateDelete != null)
{
Context.Entry(orderSubItem).State = EntityState.Detached;
orderItem.OrderSubItems.Remove(orderSubItem);
}
}
}
}
}
}
First, yes I get an exception because I'm modifying the collection of my foreach loop. so I already changed all this to a simple for classic loop.
Now my question is: Is it possible to perform this in one single nice LINQ query. I tried many things but I have nothing to post here that work a minimum.
Let me explain differently what I want:
var cart = Context.Cart
.AsNoTracking()
.Include(y => y.Orders) // where DateDelete == null
.Include(y => y.Orders.Select(z => z.OrderItems)) // where DateDelete == null
.Include(y => y.Orders.Select(z => z.OrderItems.Select(x => x.OrderSubItems))) // where DateDelete == null
.SingleOrDefault(y => y.Code == cartCode);
And I also tried this:
In your Context
, in the OnModelCreating
method:
modelBuilder.Entity<YourClass>().HasQueryFilter(p => !p.IsDeleted);