问题
Entity Framework 4.0 project.
I am currently doing my cascading deletes using an INSTEAD OF DELETE trigger.
Is there a way to just do this in my Data Model code?
I thought about adding my Data Context class via partial class. Then using ObjectStateManager.ObjectStateManagerChanged to watch for deletes, and then delete children first. The problem is that will partial I can't hook into constructor to make sure my event gets hooked up. I guess I could make a factory method that created the context, then hooked up the event...
Then in my delegate, it is a little wonky too, as I have to use minimal reflection to determin the type of element being deleted, and then delete it's children.
I feel like I must be missing something: like every Entity class should have an overrideable OnDelete() method, that I could then delete all children.
If newer versions of EF solve this, feel free to mention, but it can't be an answer, as this project is locked on v4.
Thanks.
回答1:
There is a partial method OnContextCreated
that can be used to hook up to the SavingChanges
event. Newer versions also do have built in support for this type of thing. However you can override the SaveChanges
method in DbContext
.
public partial class MyContext
{
partial void OnContextCreated()
{
SavingChanges += OnSavingChanges;
}
private void OnSavingChanges(object sender, EventArgs eventArgs)
{
var myEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Deleted)
.Where(e => e.Entity is MyEntity)
.Select(e => e.Entity).Cast<MyEntity>();
}
}
来源:https://stackoverflow.com/questions/11533390/replace-t-sql-triggers-with-entity-framework-4-0-code