How can one set some attribute in Entity (Entity Framework) to be unique? One possibility would be to make it primary key but that's not what I want.
Asked
Active
Viewed 2.4k times
24
-
[Entity 6.1 now supports](http://stackoverflow.com/a/23378448/3231778) this feature. – Evandro Pomatti Aug 01 '14 at 15:55
-
[Index(IsUnique = true)] – oCcSking Apr 29 '15 at 12:49
2 Answers
20
Entity framework doesn't support unique keys so the only way is to set the unique constraint / index in the database. It will not ensure uniqueness in the application when you try to insert / update records but the exception will be fired if you try to save non unique value to the database.

Ladislav Mrnka
- 360,892
- 59
- 660
- 670
-
3It does now since v6.1. See this answer: http://stackoverflow.com/a/23378448/28098 – z-boss Jun 13 '15 at 00:10
-
@z-boss: Beware that it is not exactly what OP may asked for. There is a difference between uniqueness in the database and in the application. Supporting unique index through data annotations will still not ensure unique value handling in the application: eg. doesn't allow using relations with unique column as primary key in the application. – Ladislav Mrnka Jun 15 '15 at 10:15
-
I needed exactly what OP wrote - ensure unique values in a column, which is not intended to be used as a key. EF v6.1 lets you specify such index as attribute now. BUT, you cannot add WHERE is not null clause. (Because I want to ensure uniqueness only for records that contain values). So, ended up creating index with SQL statement in migration. – z-boss Jun 18 '15 at 14:28
6
-
1Yes, very nice article about feature we can hopefully expect in the next major release of Entity Framework - not in 4 or 4.1. – Ladislav Mrnka May 18 '11 at 21:20
-
-
9
-
While the unique key cannot be added using a simple attribute. In Code First you can use the .Index() method to add the index in the migration class. – Robba Mar 07 '14 at 20:03