带数据注释的唯一约束
我正在使用 System.ComponentModel.DataAnnotations 命名空间来验证我的域类。如何创建自定义属性来验证属性的唯一性,无论数据库如何(例如通过某些接口)?
I'm using the System.ComponentModel.DataAnnotations
namespace to validate my domain classes. How can I create a custom attribute to validate the uniqueness of a property regardless of the database (through some interface, for example)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是我针对这种情况提出的解决方案,它只是检查表中是否有具有不同 id 的记录,该记录与正在验证的属性具有相同的值。它假定您将使用 LinqToSQL,并且任何需要进行此类验证的表都具有单个 ID 列。
我还在数据库中的基础表上设置了唯一约束。该属性允许我在表单上放置一条不错的错误消息并将其与适当的属性关联起来。
用法示例:
This is the solution I came up with for this situation, it simply checks the table for a record with a different id that has the same value for the property being validated. It assumes that you will be using LinqToSQL, and that any table on which this kind of validation is required has a single ID column.
I'd also put a unique constraint on the underlying table in the database. This attribute allows me to put a nice error message on the form and associate it with the appropriate property.
Example usage:
只需在你的模型上做这样的事情
just do something like this on your model
如果我正确理解您的意思,您应该能够创建自定义 ValidationAttribute 并通过自定义工厂获取存储库的上下文。
验证器:
您将拥有一个带有 IsUnique() 方法的 IRepository 接口。 MyRepositoryFactory 有一个名为 Create() 的静态方法,它将创建数据库所需的具体存储库。如果数据库类型发生变化,您只需更新 Factory 即可为新数据库返回一个新的 Repository。
If I am understanding you properly, you should be able to create a custom ValidationAttribute and get a context to your repository through a custom factory.
Validator:
You would have an IRepository interface with an IsUnique() method. The MyRepositoryFactory would have a static method called Create() which would create the concrete Repository necessary for your database. If the database type changes, you only need to update the Factory to return a new Repository for your new database.
我喜欢@daveb 的解决方案。不幸的是,三年后,我需要对其进行一些相当大的修改。这是他针对 EF6 更新的解决方案。希望能为某人节省一个小时左右的时间。
I love @daveb's solution. Unfortunately, three years later it required some pretty heavy modification for me. Here's his solution updated for EF6. Hopefully will save someone an hour or so of fiddling.