Home > Mobile >  EF Core 2.1 seeding data primary key
EF Core 2.1 seeding data primary key

Time:12-09

I have just run into an issue, reminiscent of chicken and egg situation.

I'm trying to seed data in EF 2.1.3. I have a class called "Sample".

public class Sample
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public bool IsActive { get; set; }
        public bool IsVisible { get; set; }
    }

I have the following seed method:

builder.HasData(
                new Sample {Id=1, IsActive = true, IsVisible = true, Name = "Test 1" },
                new Sample { Id = 2, IsActive = true, IsVisible = true, Name = "Test 2" },
                new Sample { Id = 3, IsActive = true, IsVisible = true, Name = "Test 3" }
                );

Now, this seems to have worked ok the first time I have generated the migrations

Now, however, every time I run Add-Migration command I get this error:

The seed entity for entity type 'Sample' cannot be added because another seed entity with the same key value for {'Id'} has already been added. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

Getting rid of Id values from seed data - results in this error:

The seed entity for entity type 'Sample' cannot be added because there was no value provided for the required property 'Id'.

CodePudding user response:

EF core requires keys to be added to the pocos because it needs to know which is the primary key. You can try adding data attributes like your [Key] and [Required] to your class properties

Here is a write up on data attributes

You also don’t typically have to add ID if your table is auto incrementing assuming your using a relational database

CodePudding user response:

This is the Ids has been previously added. You are inserting duplicate key values.

  • Related