我想知道这是否可能。当特定表中的值被更新时,我们希望一个函数在我们的 .NET 代码中工作。这可能是在记录插入或更新时。这可能吗?如果没有,是否有替代过程?
2 回答
你需要问几个问题。
您是否希望在数据库级别有任何业务逻辑?显然,一个数据库触发器可以做到这一点(当一个值改变时执行一些操作,即使只是非常具体的值)。
我见过一些数据库触发器很重的系统。他们的“逻辑”与 db 平台高度耦合。这样做有一些优点,但大多数人可能会说缺点太大(耦合、缺乏封装/可重用性)。
根据您正在做的事情和您的倾向,您可以:
确保所有 DAO/BusinessFunctoin 对象
object.function
在发生特定值更改时调用您的“事件”以执行您想要的操作。object.function
当某个值发生变化时,使用触发器调用您的“事件” 。您的触发器可以完成一切。
我个人倾向于选项 2,其中您有一个最小的触发器(它只是触发对您的事件调用object.function
),因此您不会将您的数据库与您的业务逻辑深度耦合。
Option 1 is fine, but may be a bit of a hassle unless you have a very narrow set of BF/DAO's that talk to this db table.field you want to watch.
Option 3 is imho the worst choice as you couple logic to your db and reduce its accessibility to your business logic layer.
Given that, here is some information toward accomplishing this via Options 2:
Using this example from MSDN: http://msdn.microsoft.com/en-us/library/938d9dz2.aspx.
This shows how to have a trigger run and call a CLR object in a project.
Effectively, in your project, you create a trigger and have it call your class.
Notice the line: [SqlTrigger(Name="UserNameAudit", Target="Users", Event="FOR INSERT")]
This defines when the code fires, then within the code, you can check your constraint, then fire the rest of the method (or not), or call another object.method
as needed.
The primary difference between going directly to the db and adding a trigger is this gives you access to all the objects in your project when deployed together.