在Entity Framework中使用唯一约束(unique)
在Entity Framework使用IndexAnnotation来创建索引,但是系统未提供能够创建组合的唯一索引。下面扩展方法可以生成唯一索引。
1 public static class TypeConfigurationExtensions 2 { 3 /// <summary> 4 /// 生成唯一索引 5 /// </summary> 6 /// <param name="property">对象属性</param> 7 /// <param name="indexName">索引名称</param> 8 /// <param name="indexOrder">索引序列</param> 9 /// <returns></returns> 10 public static PrimitivePropertyConfiguration HasUniqueIndexAnnotation( 11 this PrimitivePropertyConfiguration property, 12 string indexName, 13 int indexOrder) 14 { 15 var indexAttribute = new IndexAttribute(indexName, indexOrder) { IsUnique = true }; 16 var indexAnnotation = new IndexAnnotation(indexAttribute); 17 18 return property.HasColumnAnnotation(IndexAnnotation.AnnotationName, indexAnnotation); 19 } 20 }
使用方式
this.Property(p => p.ChainId).IsRequired().HasMaxLength(32).HasUniqueIndexAnnotation("IX_Unique_ChainId_Name", 0); this.Property(p => p.Name).IsRequired().HasMaxLength(64).HasUniqueIndexAnnotation("IX_Unique_ChainId_Name", 1);
生成的效果