我有一个表格(Id,name,itemst,otherproperties),其中Id是主键,我想创建一个唯一的复合键(name,itemst)。我如何通过Code First添加此内容,可以使用Fluent API(首选)或注释?
我有一个表格(Id,name,itemst,otherproperties),其中Id是主键,我想创建一个唯一的复合键(name,itemst)。我如何通过Code First添加此内容,可以使用Fluent API(首选)或注释?
假设你有一个名为的实体
public class MyTable
{
public int Id {get; set;}
public String Name {get; set;}
}
您可以使用复合键创建
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});
}
}
如果您更喜欢数据注释,您可以简单地将 KeyAttribute
添加到多个属性中。
public class MyTable
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] // optional
[Key]
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)] // optional
[Key]
public String Name { get; set; }
}
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}));
}