实体框架中多列的唯一键约束

实体框架中多列的唯一键约束

问题描述:

我使用的是实体框架 5.0 代码优先;

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;}
 }

我想让 FirstColumnSecondColumn 之间的组合是唯一的.

I want to make the combination between FirstColumn and SecondColumn as unique.

示例:

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?

使用 Entity Framework 6.1,您现在可以执行以下操作:

With Entity Framework 6.1, you can now do this:

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

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

属性中的第二个参数用于指定索引中列的顺序.
更多信息:MSDN

The second parameter in the attribute is where you can specify the order of the columns in the index.
More information: MSDN