Reputation: 24414
I use Entity Framework with C#.
Because actual version has nothing like unique constraint for non-key attributes, I would like (perhaps using TRANSACTIONS) atomically test if some attribute NAME is in some table (entity) and if not, then I would add the new entity and commit.
How can this be done? Or is there a better solution?
Upvotes: 0
Views: 967
Reputation: 39956
You have to create unique index for that column in database. Transaction will not help because two different instance of application or context will not work against programming level locking.
Upvotes: 1
Reputation: 33149
One way to do it, is to define the constraint on the DB.
Since Entity Framework doesn't know about constraints at the DB level, you should then script the constraint (i.e., create a .SQL file) so that you can add it to any new instances of your DB.
Another way to do it is to implement a standard Repository per entity type (such as CustomerRepository) and then to do the check in that repository's Create method. This, by itself, does not guarantee unicity since two users may at the same time create an entity with the same name, and the check won't catch it until you try to commit (i.e., SaveChanges), but that is also the case when you define the unicity constraint on the DB...
Upvotes: 1