c# - 无法在对象中插入重复的键 - 如何在 Entity Framework Core 中创建复合键

标签 c# sql sql-server entity-framework entity-framework-core

我需要使用 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).

为什么它不组合名称。因为Nameuniqie

最佳答案

本教程基于这篇文章: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; }
}

该表格是根据您的要求设计的:

design of table

基于您的问题的数据:

enter image description here

关于c# - 无法在对象中插入重复的键 - 如何在 Entity Framework Core 中创建复合键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54821778/

相关文章:

c# - DataTable 问题列的 ADO.Net DataType

c# - 表示数字序列的算法

c# - MongoDB:可以设置ID吗?

使用命名空间找不到 c#asp.net web api 文件存在

sql - 了解聚集索引

sql - Visual Studio 2012 数据库项目 - 文件路径配置

c# - CaSTLe Active Record 多个数据库连接(Oracle 和 SQL)

mysql - 左联接 - 未知列错误

sql-server - 数据库引擎调优顾问不断崩溃

sql-server - 如何使用无 DSN 连接在 Access 中创建直通查询?