实体未标记为删除的 EF4 DbContext LINQ 查询

EF4 DbContext LINQ query where entity not marked for deletion

我似乎无法找到一种方法(想知道是否确实可行)对 D​​BContext 执行 LINQ 查询,只给出未标记为删除的项目。

例如

// 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));

然后我可以执行忽略已删除对象的查询(当然不必触发 SaveChanges())吗?

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

即我只想要未标记为删除的库存实体的权重总和。

编辑: 无法使 ChangeTracker() 参考正常工作,因此最终执行了以下操作...

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();
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();

如果您出于某种原因需要从 DbContext 中获取已删除的项目。你可以这样做:

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