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.
2 Answers
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.
-
3It does now since v6.1. See this answer: stackoverflow.com/a/23378448/28098– z-bossJun 13, 2015 at 0: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. Jun 15, 2015 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-bossJun 18, 2015 at 14:28
http://blogs.msdn.com/b/efdesign/archive/2011/03/09/unique-constraints-in-the-entity-framework.aspx
also see Unique keys in Entity Framework 4
-
1Yes, very nice article about feature we can hopefully expect in the next major release of Entity Framework - not in 4 or 4.1. May 18, 2011 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.– RobbaMar 7, 2014 at 20:03