Search code examples
c#mysqlasp.net-coreentity-framework-core

Duplicate key error after adding data in a table with seeded entities


The situation is the following: I am using .NET 5 and Entity Framework. I have a seeder, which looks like that:

    public static void Seed(this ModelBuilder modelBuilder)
    {
        Entity[] entities = new Entity[]
        {
            new Entity
            {
                Id = 1,
                Description = "Test description 1"
            },
            new Entity
            {
                Id = 1,
                Description = "Test description 1"
            } 
        }
    }

My entity is the following, nothing special:

public class Entity 
{
    [Key]
    public ins Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }
    
    public IList<AnotherEntity> AnotherEntity { get; set; } = new List<AnotherEntity>();
}

I want to add another entity to the database (I am using MySQL) not from the database directly, but using EF, but when I try to do it (call .SaveChanges()), I get an error saying that there is a duplication in PK, because EF does not understand that there is already data in this table.

How can I handle the issue?


Solution

  • What I discovered is that if in the OnModelCreating method you add:

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<MyEntity>().Property(b => b.Id).ValueGeneratedOnAdd();
        }
    

    The database manages to understand that there is already seeded data and generates not duplicate Ids.