我使用实体框架5.0代码第一;

public class Entity
 {
   [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public string EntityId { get; set;}
   public int FirstColumn  { get; set;}
   public int SecondColumn  { get; set;}
 }

我想让FirstColumn和SecondColumn的组合是唯一的。

例子:

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

有办法吗?


当前回答

使用实体框架6.1,你现在可以这样做:

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

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

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

其他回答

最近添加了一个组合键的唯一性2列使用'chuck'推荐的方法,谢谢@chuck。只有这条路在我看来比较干净:

public int groupId {get; set;}

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

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

使用实体框架6.1,你现在可以这样做:

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

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

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

你应该把Index属性放在实体类的顶部,并在string[]中定义多个键。

[Index("FirstColumn", "SecondColumn", IsUnique = true, Name = "My_Unique_Index")]
public class Entity    

 {
   [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public string EntityId { get; set;}
   public int FirstColumn  { get; set;}
   public int SecondColumn  { get; set;}
 }

对于那些在寻找2021年解决方案的人来说,公认答案的工作版本现在应该是这样的:

[Index(nameof(FirstColumn), nameof(SecondColumn), IsUnique = true)]
public class Entity
 {
   [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public string EntityId { get; set;}
   public int FirstColumn  { get; set;}
   public int SecondColumn  { get; set;}
 }

因此,注释应该存在于模型上,而不是单独的列上。还要注意nameof()语法。

这个答案来自于官方文档:https://learn.microsoft.com/en-us/ef/core/modeling/indexes?tabs=data-annotations

您需要定义一个复合键。

使用数据注释,它看起来像这样:

public class Entity
 {
   public string EntityId { get; set;}
   [Key]
   [Column(Order=0)]
   public int FirstColumn  { get; set;}
   [Key]
   [Column(Order=1)]
   public int SecondColumn  { get; set;}
 }

你也可以在覆盖onmodelcreation时通过指定modelBuilder来做到这一点:

modelBuilder.Entity<Entity>().HasKey(x => new { x.FirstColumn, x.SecondColumn });