I'm using Entity Framework 5.0 Code First;
public class Entity
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string EntityId { get; set;}
public int FirstColumn { get; set;}
public int SecondColumn { get; set;}
}
I want to make the combination between FirstColumn
and SecondColumn
as unique.
Example:
Id FirstColumn SecondColumn
1 1 1 = OK
2 2 1 = OK
3 3 3 = OK
5 3 1 = THIS OK
4 3 3 = GRRRRR! HERE ERROR
Is there anyway to do that?
Completing @chuck answer for using composite indices with foreign keys.
You need to define a property that will hold the value of the foreign key. You can then use this property inside the index definition.
For example, we have company with employees and only we have a unique constraint on (name, company) for any employee:
Now the mapping of the Employee class:
Note that I also used @niaher extension for unique index annotation.