Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add unique non primary-key field to entity using Entity Framework 4.1?

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?

like image 802
y.selivonchyk Avatar asked Sep 05 '11 09:09

y.selivonchyk


2 Answers

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; }
like image 61
Jayantha Lal Sirisena Avatar answered Oct 19 '22 20:10

Jayantha Lal Sirisena


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

like image 42
Smudge202 Avatar answered Oct 19 '22 18:10

Smudge202