Is it possible to remove child from collection and resolve issues on SaveChanges?

为君一笑 提交于 2019-11-27 06:45:50
Slauma

I don't know if the following is a solution for you but Entity Framework supports Identifying Relationships. In such a relationship the foreign key of the child entity (dependent) to the parent (principal) must be part of the (composite) primary key of the child entity. For example - with DbContext data annotations - your model classes have to look like this:

public class Order
{
    [Key]
    public int OrderId { get; set; }

    public ICollection<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    [Key, ForeignKey("Order"), Column(Order = 1)]
    public int OrderId { get; set; }

    [Key, Column(Order = 2)]
    public int OrderLineId { get; set; }

    public Order Order { get; set; }
}

You can make the OrderLineId an autogenerated identity if you want. Important is only that the FK to Order is part of the PK.

A code like this for example...

using (var ctx = new MyContext())
{
    var order = ctx.Orders.Include("OrderLines").Single(o => o.OrderId == 1);
    var orderLineToDelete = order.OrderLines
        .FirstOrDefault(ol => ol.OrderLineId == 5);
    if (orderLineToDelete != null)
        order.OrderLines.Remove(orderLineToDelete);

    ctx.SaveChanges();
}

...would indeed delete the orderLineToDelete from the database.

More details are here in section "Considerations for Identifying and Non-identifying Relationships".

Steve Wilkes

As you're finding, if you just remove an Entity from a collection the Entity hangs around attached to the object context and gives you an error when you call SaveChanges(); I've used Domain Events to enable a tidy way of removing the Entity from the object context via a Repository.

I've detailed this approach in my answer to this question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!