【发布时间】:2014-08-22 18:32:05
【问题描述】:
我有一个表(Id、name、itemst、otherproperties),Id 是主键,我想要一个唯一的复合键(name、itemst)。如何通过 fluent API(首选)或注释首先使用代码添加它?
【问题讨论】:
标签: c# entity-framework
我有一个表(Id、name、itemst、otherproperties),Id 是主键,我想要一个唯一的复合键(name、itemst)。如何通过 fluent API(首选)或注释首先使用代码添加它?
【问题讨论】:
标签: c# entity-framework
假设您有一个名为
的实体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; }
}
【讨论】:
这是一个示例,展示了如何通过 fluent API 创建复合唯一键。复合键由 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}));
}
【讨论】: