BLoB
BLoB

Reputation: 9725

EF4 DbContext LINQ query where entity not marked for deletion

I can't seem to find a way to (wondering if it is indeed possible) to perform a LINQ query on the DBContext giving only items that are not marked for deletion.

e.g.

// Mark one or more items in the DBContext for deletion.
(from di in DbContext.DeliveryItems where di.Id == myId select di).ToList().ForEach(di => this.Context.DeleteObject(di));

Can I then perform a query that will ignore the deleted objects (without of course having to fire a SaveChanges())?

decimal? weight = (from s in this.Context.Stocks
                   where di.Id == myId
                   select s.GrossWeight).Sum();

i.e. I only want the sum of weights for stock entities that have not been marked for deletion.

EDIT: Couldn't get ChangeTracker() reference working so ended up doing the following...

List<int> deletedDeliveryItems = this.Context.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Deleted)
                                 .Where(x => x.EntityKey.EntitySetName == "DeliveryItems")
                                 .Select(x => ((DeliveryItem)x.Entity).Id).ToList();

decimal? sumWeightOfDeletedDeliveryItems = (from s in DbContext.Stocks
                                            where deletedDeliveryItems.Count > 0 &&
                                            deletedDeliveryItems.Contains(s.Id)
                                            select s.GrossWeight).Sum();

Upvotes: 0

Views: 395

Answers (1)

Magnus
Magnus

Reputation: 46919

var delete = (from di in DbContext.DeliveryItems where di.Id == myId select di).ToList();

delete.ForEach(di => this.Context.DeleteObject(di));

decimal? weight = (from s in this.Context.Stocks
                   where !delete.Select(di => di.Id).Contains(s.SomeId)
                   select s.GrossWeight).Sum();

If you for some reason need to get the deleted items from the DbContext. You can do this:

var deleted = context.ChangeTracker.Entries()
               .Where(x => x.State == System.Data.EntityState.Deleted)
               .Select(x=> x.Entity).ToList();

Upvotes: 1

Related Questions