views:

29

answers:

1

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 ?

A: 

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.

NickLarsen
I am using entity framework so every of those properties represent a column in the database, and the UniqueAttributeValidator should check if the value of the property is unique in the database
Filip
Gimme the codez?
NickLarsen