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?

1

2 Answers 2

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; }
Sign up to request clarification or add additional context in comments.

3 Comments

As of EF 6.1 the [Index(IsUnique = true)] data annotation is available
Yeah it's not released yet though.
The nuget package was released on 3/17/14..
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

2 Comments

That is answer pointing to non existing API. No EF version supports this yet.
New link supported by CTP5 added, that any use?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.