代码之家  ›  专栏  ›  技术社区  ›  neofetter

观察者与触发器

  •  3
  • neofetter  · 技术社区  · 17 年前

    大家的共识是什么?

    如果在给定操作后需要更改数据库,是否使用观察者模式并让框架/应用程序为您处理更新?还是绕过应用程序,将更新委托给数据库触发器?

    显然,触发速度更快,但值得吗?

    3 回复  |  直到 17 年前
        1
  •  3
  •   Andre Gallo    17 年前

    当我们使用LINQ2SQL时,覆盖SubmitChanges()方法很容易完成此任务。我们的主要目标是在表中进行审计。代码如下所示:

        /// <summary>
        /// Sends changes that were made to retrieved objects to the underlying database, 
        /// and specifies the action to be taken if the submission fails.
        /// NOTE: Handling this event to easily perform Audit tasks whenever a table gets updated.
        /// </summary>
        /// <param name="failureMode">The action to be taken if the submission fails. 
        /// Valid arguments are as follows:<see cref="F:System.Data.Linq.ConflictMode.FailOnFirstConflict"/>
        /// <see cref="F:System.Data.Linq.ConflictMode.ContinueOnConflict"/></param>
        public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)
        {
            //Updates
            for (int changeCounter = 0; changeCounter < this.GetChangeSet().Updates.Count; changeCounter++)
            {
                object modifiedEntity = this.GetChangeSet().Updates[changeCounter];
                SetAuditStamp(this, modifiedEntity, ChangeType.Update);
            }
    
            //Inserts
            for (int changeCounter = 0; changeCounter < this.GetChangeSet().Inserts.Count; changeCounter++)
            {
                object modifiedEntity = this.GetChangeSet().Inserts[changeCounter];
                SetAuditStamp(this, modifiedEntity, ChangeType.Insert);
            }
            base.SubmitChanges(failureMode);
    

    我们特别不喜欢使用触发器,因为它们总是隐藏在数据库中,很难解决可能出现的问题。。。有了它,你只需要开始调试它,找出失败的原因,例如。。。

        2
  •  3
  •   Kieveli    17 年前

    我使用触发器,但触发器通常是特定于数据库的。如果您计划支持多个数据库服务器,那么一定要找到一种在代码中涵盖它的方法。如果您确定将使用特定的DB服务器,那么您的数据完整性将因触发器而受到欢迎。

        3
  •  2
  •   Tony Andrews    17 年前

    除非您支持多个DBMS,否则您的框架在未来5年内(比如)比您选择的DBMS更有可能发生变化。此外,将来可能需要支持其他形式的输入,例如网页或移动设备。将这些操作放入数据库触发器意味着无论触发它们的应用程序是什么,都将执行这些操作。

    推荐文章