用Entity Framework 4.0代码替换T-SQL触发器? [英] Replace T-SQL triggers with Entity Framework 4.0 code?

查看:358
本文介绍了用Entity Framework 4.0代码替换T-SQL触发器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实体框架4.0项目。

我目前正在使用INSTEAD OF DELETE触发器进行级联删除。

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?

我想通过部分类添加我的Data Context类。然后使用ObjectStateManager.ObjectStateManagerChanged来监视删除,然后再次删除子项。问题是,部分我不能挂钩到构造函数,以确保我的事件被挂起。我想我可以做一个创建上下文的工厂方法,然后挂起事件...

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.

我觉得我必须缺少一些东西:像每个Entity类都应该有一个可重写的OnDelete()方法,我可以删除所有的孩子。

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.

如果新版本的EF解决了这一点,请随时提及,但不能是回答,因为这个项目被锁在v4上。

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.

谢谢。

推荐答案

p>有一个部分方法 OnContextCreated 可用于连接到 SavingChanges 事件。较新的版本也有内置的支持这种类型的东西。但是,您可以在 DbContext 中覆盖 SaveChanges 方法。

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>();
    }
}

这篇关于用Entity Framework 4.0代码替换T-SQL触发器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆