开发者

Unique Validation Attribute MVC 2

开发者 https://www.devze.com 2023-01-11 01:55 出处:网络
In my project I have several classes with properties that should be unique, and I want to write a custom attribute that can be used on all the properties. For example I have class User with property u

In my project I have several classes with properties that should be unique, and I want to write a custom attribute that can be used on all the properties. For example I have class User with property username and class Application with property name that should be unique and I want to be able to do this:

 [Unique(ErrorMessage = "Username alreadey exists")]
 public string username {get;set;}

 [Unique(ErrorMessage = "开发者_开发知识库Name alreadey exists")]
 public string name {get; set;}

Can someone please tell how to do this ?


Since properties are unique per context, you should verify uniqueness within the context's add functionality. In other words, this attribute should do nothing when you create a random instance of your object, but the collection you add it to should check for properties which have the Unique attribute and verify the new entity satisfies those constraints, or reject it.

0

精彩评论

暂无评论...
验证码 换一张
取 消