24

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.

yoozer8
  • 7,361
  • 7
  • 58
  • 93
Cartesius00
  • 23,584
  • 43
  • 124
  • 195

2 Answers2

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
  • 3
    It 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

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

Community
  • 1
  • 1
cheedep
  • 937
  • 6
  • 19