I use Entity Framework 4 and I have parent - child relation with \"Cascade Delete\" set. So i would expect when i remove a child from the parent that the child is deleted wh
I use this extension in order not to add a method in DAL just to delete an entity (code taken from http://blogs.msdn.com/b/alexj/archive/2009/06/08/tip-24-how-to-get-the-objectcontext-from-an-entity.aspx):
public static void Delete(this EntityCollection collection, T entityToDelete) where T : EntityObject, IEntityWithRelationships
{
RelationshipManager relationshipManager = entityToDelete.RelationshipManager;
IRelatedEnd relatedEnd = relationshipManager.GetAllRelatedEnds().FirstOrDefault();
if (relatedEnd == null)
{
throw new Exception("No relationships found for the entity to delete. Entity must have at least one relationship.");
}
var query = relatedEnd.CreateSourceQuery() as ObjectQuery;
if (query == null)
{
throw new Exception("The entity to delete is detached. Entity must be attached to an ObjectContext.");
}
query.Context.DeleteObject(entityToDelete);
collection.Remove(entityToDelete);
}
So I then delete an entity like Order.Products.Delete(prod)
.
Constraints to use the extension are:
- Entity must have relationships;
- Entity must be attached to ObjectContext.