Using EntityFramework Core 2.2 to seed data that has a database generated key

ef-core-2.2 entity-framework-core entity-framework-core-migrations

Question

I'm using EF Core 2.2, using a code first approach.

I have my entity class:

public class Client
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int ClientID { get; set; }
    public string Name { get; set; }
}

and I'm seeding my data like so:

var client = new Client { Name = "TestClient"};
modelBuilder.Entity<Client>().HasData(client);

But I receive an error when trying to add a migration:

The seed entity for entity type 'Client' cannot be added because a non-zero value is required for property 'ClientID'. Consider providing a negative value to avoid collisions with non-seed data.

The ClientID should be automatically generated and I don't want to specify it. Is there a workaround to this or has this functionality simply not been implemented yet?

1
4
2/21/2019 3:09:57 PM

Accepted Answer

With seed data, you must specify the key. Otherwise it won't know which record to ensure is there. It is documented here.

7
2/21/2019 3:17:24 PM


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