My sql database doesn't allow 2 records to be added with the same number. If I try to create a record with a previously used number or edit a record to use a previously used number, it doesn't allow it and returns to the edit/create page with an asterisk by the subcontract number field. I would like to add a Rule Violation for this so an appropriate message can be displayed. I tried adding this:
if (db.subcontracts.Count(s => s.subcontract_no == subcontract_no) > 0)
yield return new RuleViolation("Subcontract number already exists", "subcontract_no");
When writing this, I was only thinking of the Create method. The problem here is it finds a violation every time I edit a record, even if the subcontract_no hasn't changed. So, I guess I need it to find a violation when the record is created and when edited if the subcontract_no is changed. But, it can't "find itself" and create a rule violation. How can I do this?