[英]How to add a composite unique key using EF 6 Fluent Api?
I have a table (Id, name, itemst, otherproperties), Id is the primary key and I want a unique composite key (name, itemst). 我有一个表(Id,name,itemst,otherproperties),Id是主键,我想要一个唯一的复合键(name,itemst)。 How can I add this using code first either by fluent API (preferred) or annotation?
如何使用代码首先通过流畅的API(首选)或注释添加此代码?
Let say you have a entity named 假设您有一个名为的实体
public class MyTable
{
public int Id {get; set;}
public String Name {get; set;}
}
you can create composite key using 您可以使用创建复合键
public class YourContext : DbContext
{
public DbSet<MyTable> MyTables { get; set; }
protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Entity<MyTable>().HasKey(table => new {table.Id, table.Name});
}
}
if you prefer data annotation you can simple add KeyAttribute
to multiple properties 如果您更喜欢数据注释,则可以将
KeyAttribute
简单地添加到多个属性中
public class MyTable
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] // optional
[Key]
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)] // optional
[Key]
public String Name { get; set; }
}
Here is an example showing how to create a composite unique key via fluent API. 下面是一个示例,说明如何通过流畅的API创建复合唯一键。 The composite key consists of ProjectId and SectionOdKey.
复合键由ProjectId和SectionOdKey组成。
public class Table
{
int Id{set;get;}
int ProjectId {set;get;}
string SectionOdKey{set;get;}
}
public class TableMap : EntityTypeConfiguration<Table>
{
this.Property(t => t.ProjectId).HasColumnName("ProjectId")
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_ProjectSectionOd", 1){IsUnique = true}));
this.Property(t => t.SectionOdKey).HasColumnName("SectionOdKey")
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_ProjectSectionOd", 2){IsUnique = true}));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.