How can I use validation to enforce uniqueness of a property in ASP.NET MVC 2?
Imagine an object with a field that cannot have a duplicate value in the database. My first instinct was to create a unique attribute that I could apply as a data annotation to the property. This unique attribute will go into the database and check if the value exists. This will work when the create method is executed, but the update fails. When updating, I would get a double value error for every unique field in my entity whose value I don't want to change. What would be a good way, or established practice, to accomplish this in ASP.NET MVC 2 in a way that fits well with ModelState? Passing the id of my object to the attribute validator can work by checking if the duplicate value found is the same object I'm updating, but I don't know.how to get this data from validation.
Please forgive me if this is a silly question or if it is worded incoherently. It's almost 3 AM and I've been coding since morning yesterday.
a source to share
For this kind of validation, I would let the database do what it already does so well. Make sure your database has a unique constraint and allows it to report a bug if you break it. Then you can add the error to the model errors (with a nice friendly bit of text, not just using the SQL error).
If you choose to check it yourself, you can work around the UPDATE problem by excluding the current record ...
SELECT COUNT(*)
FROM myTable
WHERE myTable.UniqueValue = 'ShouldBeUnique'
AND myTable.Id <> 5
In this example, you use the ID of the record to be updated so that you don't check it, which means that you just check other records to see if they contain a unique value.
a source to share