EF 4.1 code-first adding a trigger to a table

可紊 提交于 2019-11-30 06:38:10
Ladislav Mrnka

Using custom initializer which will execute CREATE TRIGGER SQL command is the only option if you want EF to create trigger for you (similar code like here). Also don't forget to include SET NOCOUNT ON at the beginning of the trigger code.

But there is more complex problem related to trigger's logic. If you want trigger which will modify data passed to the database you must understand that changes done by trigger will not be reflected in your current context. Context will still only know entity with data you passed to the database. This is normally solved by setting properties modified by trigger as DatabaseGeneratedOption.Computed for update or DatabaseGeneratedOption.Identity for insert. In such case you cannot modify properties in your application and they must be modified in the database. EF will ensure that these properties are selected after modification and passed to the entity. The problem is that this doesn't work with code-first.

I'm not entirely sure what you mean. If you want an actual SQL trigger on the table, then I'd create the trigger, as normal, in SQL. If you mean you want some kind of processing/updating to occur in your code whenever one of you entity sets is modified, then I think you'd want to do a custom method that would be called whenever that entity set is updated.

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