我需要使用 Entity Framework Core
创建composite
键
这是我的课
public partial class MasterType
{
[DataMember(Name = "Id")]
[Key]
public string Id { get; set; }
[Required]
[DataMember(Name = "Name")]
[Key]
public string Name { get; set; }
}
这是我的 Configuration
类,它帮助我创建composite
属性
public class MasterTypeConfigurations : BaseEntityConfigurations<MasterType>
{
public override void Configure(EntityTypeBuilder<MasterType> builder)
{
base.Configure(builder);
// composite key
builder.HasKey(c => new { c.Id, c.Name});
}
}
我正在使用 Entity Framework 核心的迁移
功能
这是生成的迁移脚本
migrationBuilder.CreateTable(
name: "MasterTypes",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_MasterTypes", x => new { x.Id, x.Name });
});
但是,当我执行插入SQL
时,我收到错误
INSERT INTO [dbo].[MasterTypes] ([Id] ,[Name]) VALUES ('CA8301','Type1')
INSERT INTO [dbo].[MasterTypes] ([Id] ,[Name]) VALUES ('CA8301','Type2')
Cannot insert duplicate key in object. The duplicate key value is (C8301, C8301).
为什么它不组合名称
。因为Name
是uniqie
最佳答案
本教程基于这篇文章:Composite Keys
Entity Framework Core 支持复合键 - 从数据库中的两个或多个字段生成的主键值。但是,与以前版本的 Entity Framework 不同,您不能使用 Key 属性来定义组合键。这只能通过 Fluent API 来完成。
class Program
{
static void Main(string[] args)
{
using (var db=new SampleContext())
{
db.Database.EnsureCreated();
db.MasterTypes.Add(new MasterType()
{
Id = "CA8301",
Name = "Type1"
});
db.MasterTypes.Add(new MasterType()
{
Id = "CA8301",
Name = "Type2"
});
db.SaveChanges();
}
}
}
public class SampleContext : DbContext
{
public DbSet<MasterType> MasterTypes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MasterType>()
.HasKey(o => new { o.Id, o.Name});
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=.;Database=MyDb;Trusted_Connection=True;");
}
}
public class MasterType
{
public string Id { get; set; }
public string Name { get; set; }
}
该表格是根据您的要求设计的:
基于您的问题的数据:
关于c# - 无法在对象中插入重复的键 - 如何在 Entity Framework Core 中创建复合键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54821778/