You can define a custom DataAnnotation attribute which would validate the uniqueness of the the property to which it is applied.
I have attached a sample implementation of such attribute class. It checks if there are entities of the same type with the same property value in the database. If there are such entities their primary keys are evaluated against that of the entity which property is currently being validated. Please note that this implementation would access the database each time a property is being validated and this may lower the performance of your application.
Since such attribute would normally be applied to a small number of different properties, we recommend adding it manually to the properties of your persistent classes. In case you are using a Domain Model
which would regenerate its persistent classes and context each time it is saved, it may be a good idea to write a unit test which checks if the required properties have the attribute added. The sample Unique attribute can be applied to a property as follows:
As an argument, the full name
of the model`s context class is passed. In the code snippet above, "TestDataAnnotations"
is the namespace
containing the model and "EntitiesModel"
is the name
of the model`s context class.
Note that even when validating the uniqueness of a value in your application, it is still highly recommended to specify the respective column as unique
. This will prevent other applications that may work with the same database from inserting invalid values.
I hope this helps.
OpenAccess ORM Q3 2013 simplifies your model operations even further providing you with greater flexibility. Check out the list of new features
shipped with our latest release!