How to add unique non primary-key field to entity using Entity Framework 4.1?
-
25-10-2019 - |
Question
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?
Solution
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; }
OTHER TIPS
Check out the unique constraints, I think that's what you're looking for?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow