Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set a unique constraint using Entity Framework Code First?

I want to enforce Unique constraint in a table & I am using Entity Framework Code-First.

Is it possible to add a unique constraint using EF 6 as i believe in earlier versions it was not possible.

like image 716
subi_speedrunner Avatar asked Nov 10 '14 06:11

subi_speedrunner


People also ask

How does CODE first work in Entity Framework?

Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…

Which is better code first or database first in Entity Framework?

3)Database Version Control Versioning databases is hard, but with code first and code first migrations, it's much more effective. Because your database schema is fully based on your code models, by version controlling your source code you're helping to version your database.


1 Answers

It appears that the unique constraint feature that was scheduled to release with Version 6 got pushed to 6.1.

With EF 6.1, you can define a constraint using the Index attribute as shown below:

[Index("IX_FirstAndSecond", 1, IsUnique = true)] public int FirstColumn { get; set; }  [Index("IX_FirstAndSecond", 2, IsUnique = true)] public int SecondColumn { get; set; } 

OR

You can use Fluent API as shown here in MSDN

like image 158
SBirthare Avatar answered Sep 22 '22 16:09

SBirthare