唯一值验证:更新持久层之前还是之后?
我想知道验证视图字段值在实体集中唯一的最佳方法是什么:在更新持久层之前或之后? 涉及的db字段具有唯一约束,其表映射到EF模型。 我在实体集中看到了两种唯一值验证的方法:
- 在将更改保存到数据库之前(在模型更新期间或通过使用自定义 DataAnnotations 装饰模型)
- 之后将更改保存到数据库(通过在存储库或控制器中处理持久层生成的 UpdateException)
使用第一种方法,我需要查询数据库以检查唯一性,因此任何视图更新都需要数据库选择和数据库更新。
使用第二种方法,不需要额外的选择,但很难识别错误类型和违规字段。
我更喜欢方法2,但是确定插入/更新是否由于唯一约束而失败的问题迫使我选择方法1。
或者还有其他方法吗?
I'm wondering what's the best method for validating a view field value to be unique in an entityset: before or after the update to persistence layer?
The involved db field has an unique constraint, and its table is mapped to an EF model.
I see two ways for unique value validation in an entityset:
- before saving changes to db (during model update or by decorating with custom DataAnnotations the model)
- after saving changes to db (by handling in the repository or controller the UpdateException generated by the persistence layer)
With the 1st method I need to query the db for checking the uniqueness, so any view update will require both a db select and a db update.
With the 2nd method, the additional select is not required, but it is difficult to identify the error type and the offending field.
I would prefer method 2, but the problem for determining if the insert/update failed due to a unique constraint force me to choose method 1.
Or is there another way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查唯一约束的首选和推荐方法是通过自定义 DataAnnotation 属性从 UI 进行检查。使用这种方法,您必须编写一些代码,但这就是所有站点为检查唯一性约束所做的事情。然而,asp.net mvc 3 提供了 RemoteAttribute 开箱即用,用于检查唯一性约束。我建议使用第一种方法,因为如果您以良好的方式组织它,一些微小的 ajax 调用不会对性能产生明显的影响。
The preferred and recommended way for checking unique constraint is from UI by custom DataAnnotation attribute. with this method you have to write a little code but this is what all the sites have been doing for checking uniqueness constraint. asp.net mvc 3 however provides RemoteAttribute out of the box to check uniqueness constraint. i would recommend using first method because some tiny ajax calls won't make noticeable effect on performance provided that you have organized it in a good manner.