After much research it seems Entity Framework 4.4 doesn't support Unique constraints. Yes it can & should be done at the database, but I'd much prefer it happen in model validation so the warning to user is prettier.
It would be ideal for programmers to be able to decorate the property with a [Unique] attribute and it should be possible somehow, eg.:
public class UserGroup
{
public int UserGroupID { get; set; }
[Required]
[Unique]
public string Name { get; set; }
[Required]
public string Description { get; set; }
}
Options I'm considering:
1) Have the repository do some extra work at SaveChanges(), scan for [Unique] attributes on modified entities and hit the database to check uniqueness. Downside: this validation only happens when we call SaveChanges(), ideally it can happen earlier (eg. when the UI control validates).
2) Give the UserGroup model a lazy-loaded navigation property to AllUserGroups:
public virtual ICollection<UserGroup> AllUserGroups { get; set; }
Then program UniqueAttribute{} to scan this property and check the values etc.
QUESTION: how can I configure Entity Framework (code first) to load all records into this "navigation property"? It only seems to want a navigation property with foreign keys etc while I just want them all.
3) Manually code this validation in the UI - terrible & absolute last resort.
QUESTION: are there any better options for enforcing a Unique Constraint via validation at the model level?
Regards, -Brendan