EF 4: Removing child object from collection does not delete it - why?

前端 未结 5 1354
执念已碎
执念已碎 2020-11-29 09:02

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

5条回答
  •  遥遥无期
    2020-11-29 09:34

    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.

提交回复
热议问题