Replace T-SQL triggers with Entity Framework 4.0 code?

雨燕双飞 提交于 2019-12-13 04:17:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!