9

We are using Entity Framework 4.1 Code first.

We've got user entity with primary key set to UserId and need UserLogin to be unique. How can it be done?

y.selivonchyk
  • 8,987
  • 8
  • 54
  • 77
  • possible duplicate of [Unique key with EF code first](http://stackoverflow.com/questions/5701608/unique-key-with-ef-code-first) – Ladislav Mrnka Sep 05 '11 at 09:54

2 Answers2

15

Entity Framework does not support Unique constraints. You can create them using a SQL Query to generate unique constrains when initializing the database. Write your custom initializer for the model and execute SQL command to generate constrain.

Edit

Now (EF 6.1 onwards )you can easily have unique constrains ,

[Index("UserLoginIndex", IsUnique = True)]
public string UserLogin { get; set; }
Ehsan88
  • 3,569
  • 5
  • 29
  • 52
Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92
2

Check out the unique constraints, I think that's what you're looking for?

http://weblogs.asp.net/manavi/archive/2011/01/23/associations-in-ef-code-first-ctp5-part-3-one-to-one-foreign-key-associations.aspx

Smudge202
  • 4,689
  • 2
  • 26
  • 44