Deleting child objects in Entity Framework when using POCO
I'm using POCO with EF4 and have problem deleting a child object from the parent. Consider the following scenario:
public class Order
{
public List<OrderItem> Items { get; private set; }
}
I need to delete an OrderItem from an Order object like:
myOrder.Items.Remove(0);
I expect EF to keep track the changes and delete the associated OrderItem when I call ObjectContext.SaveChanges(开发者_如何学编程).
However, I have realized this is not possible without calling Context.DeleteObject(). I believe this is not a true POCO way as my domain model shouldn't be aware of my persistence infrastructure.
Does anyone have a work around this issue?
Cheers, Mosh
However, I have realized this is not possible without calling Context.DeleteObject(). I believe this is not a true POCO way as my domain model shouldn't be aware of my persistence infrastructure.
I would not follow your interpretation. If you have in-memory collections of orders and order items (ignoring the persistence infrastructure), it's a difference if you only remove an item from the order's item collection or if you also delete the item from the in-memory repository. It might be possible that you want to remove the item only from one order, keep it existing and assign it to another order. (It wouldn't probably make much sense in case of orders and order items, but that's business logic and your POCOs and their relationships cannot know that you want to delete the item from the repository everytime you remove it from an order.)
So, you have to tell explicitely that the item should be deleted from the repository - for an in-memory repository and for a persistence related repository as well. You have to call DeleteObject
for the item, there is no workaround to avoid this.
What referential integrity do you have setup in the DB? You have only asked for the orderitem to be removed from the item - not for it to be deleted, and that is what is happening.
精彩评论