Cannot insert duplicate key in object - How to create composite key in Entity Framework Core

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

Question

I have a requirement to create composite key using Entity Framework Core

This is my class

public partial class MasterType
{
    [DataMember(Name = "Id")]
    [Key]
    public string Id { get; set; }

    [Required]
    [DataMember(Name = "Name")]
    [Key]
    public string Name { get; set; }
}

Here is my Configuration class, which help me to create composite properties

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});
    }
}

I am using migration feature of entity framework core

Here is the generated migration script

  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 });                 
            });

But, when I execute the insert SQL, I get error

 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).

Why it's not combining the Name. Because Name is uniqie

1
1
2/22/2019 7:05:50 AM

Popular Answer

The tutorial required on this link is available :Composite Keys

Entity Framework Core supports composite keys - primary key values generated from two or more fields in the database. However, unlike in previous versions of Entity Framework, you cannot use the Key attribute to define composite keys. This can only be done via the 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; }
}

The table is designed according to your request:

design of table

the data based on your question:

enter image description here

1
2/22/2019 9:12:26 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow