Skip to main content

Posts

Showing posts from 2013

Adding Unique Constraints with Entity Framework Code First

Entity Framework Code First is a great way to define and maintain your database within your application it self. While it poses a nice set of complementing libraries like Data Annotations and Fluent Configurations which helps you specially in defining phase of your database, it would give you a headache if you try to define a unique constraint on a column. For example in the users table of your application you could probably have an int ID column which would serve as the primary key and you might need to make your Username column a unique one. Since you are using EF Code First you will soon find out there is no direct way to accomplish this requirement. Unfortunately fluent configurations doesn't have syntax like HasUnique(u => u.Username); I asked the same question in stackoverflow , but didn't get a convincing answer. Since there is no direct support from EF for this you could take one of following alternatives to achieve it. Approach 1 :