Is there a way to cascade delete entities without modifying foreign keys in DB and without modifying edmx? I have DB with over 100 tables referenced using foreign keys with Delete Rule = No Action.
I found this this beautiful code in "Entity Framework 6 Recipes" book. But it for ObjectContext and I need for the DbContext.
private static void DeleteRelatedEntities<T>(T entity, test123Entities1 context)
where T : EntityObject
{
var entities =
((IEntityWithRelationships) entity).RelationshipManager.GetAllRelatedEnds()
.SelectMany(e => e.CreateSourceQuery().OfType<EntityObject>())
.ToList();
foreach (var child in entities)
{
DeleteRelatedEntities(child, context);
context.DeleteObject(child);
}
context.SaveChanges();
}
It's possible to use this method with this convertion
//var ddd = ((IObjectContextAdapter)context).ObjectContext;
but then I also need similar adapter to convert my POCO to EntityObject.
Any suggestions?
Thank you.
That is BAD code.
StackOverflowException
- verified right now by copying your code snippet into my test solution.SaveChanges
is called in recursive function - each execution will flush to database every unprocessed change from the context - not only changes done in that specific recursion step. It also requires TransactionScope
if you want to keep everything in single atomic operation.EntityObject
- OMG why book about EF6 contains code related to EntityObject
class? Looks like a cash cow with content copied from old version about EF4. I don't have anything against ObjectContext API but EntityObject
? Really?In short make yourselves a favor and fix your DB and entity model if you want to have cascade delete or don't use cascade delete and manually (preferably with direct SQL) delete dependencies. There is also option to use triggers to execute that SQL but I don't consider triggers as a good option.