Entity Framework: How to delete child using generic repository pattern?

entity-framework entity-framework-6 repository-pattern

Popular Answer

Not from the database, but from the Parent, you are eliminating the children. As a side note, here's a shorter way to accomplish it:

foreach (var child in p.Children
                       .Where(child => !sourceChildIDs.Contains(child.ChildID))
                       .ToList())
{
    p.Children.Remove(child);
}

But this merely dissociates parents and kids from one another. To be safe, EF believes that you simply want to remove the children's foreign key reference, not the children themselves.

Therefore, you must delete the children from the database by substituting the preceding sentences with

var delIds = p.Children.Where(child => !sourceChildIDs.Contains(child.ChildID))
                       .Select(c => c.ChildID).ToList();
_repository.Delete<Child>(c => delIds.Contains(c.ChildID));

This is a really unusual generic repository implementation, by the way. Typically, generic repositories are created for a single type, as defined byGenericRepository<T> . These repositories often work together in a single unit of work that also saves the modifications, while sharing a single context instance.

0
5/26/2016 10:20:09 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow