开发者

Remove() From Collection Does Not Mark Object As Deleted - EF4

I'm using POCO generated classes - any way that I can tweek the template so that when I remove from a child collection, the item removed is al开发者_开发百科so deleted from the db ?

Or maybe in the partial class I can override something, catch an event ..?

Basically I want Order.OrderDetails.Remove(orderDetail) to remove the orderDetail from db.

I do not want to access the context and do context.OrderDetails.Delete(orderDetail).


When you remove an object from a collection navigation property, Entity Framework removes the relationship between the objects (nulling the property on the child object that refers to its parent).

If you want to delete a record, you need to mark the object as State = EntityState.Deleted. You can either do that by accessing the context, or if you don't want to, a workaround would be to identify the child objects that have been orphaned in the ChangeTracker, and set their State to Deleted there.

var orphans = context.ChangeTracker.Entries().Where(e => e.State == EntityState.Modified && typeof(e.Entity) is ChildType);
foreach (DbEntityEntry orphan in orphans)
{
    orphan.State = EntityState.Deleted;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜