EF 4.1代码优先在表中添加触发器 [英] EF 4.1 code-first adding a trigger to a table
问题描述
将触发器添加到通过EF 4.1的代码优先方法创建的表中的最佳方法是什么?
我要考虑的一种方法是在OnModelCreating或初始化Db上下文时执行自定义SQL查询.
有更好的主意吗?
如果您想让EF为您创建触发器(这不起作用以代码优先.What is the best way to add a trigger to a table created by code-first approach with EF 4.1?
A way I'm cosidering is to execute a custom SQL query either in OnModelCreating or when Db context is being initialized.
Is there a better idea?
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.
这篇关于EF 4.1代码优先在表中添加触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!