We are using Entity Framework Code First with Foreign Key relationships. We investigating on ways on handling removing objects from an entities ICollection in our applicatio
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".
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.