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?
Database. EnsureCreated() to create a new database containing the seed data, for example for a test database or when using the in-memory provider or any non-relational database. Note that if the database already exists, EnsureCreated() will neither update the schema nor seed data in the database.
Seed Data in Entity Framework Core So as soon as we execute our migration files to create and configure the database, we want to populate it with some initial data. This action is called Data Seeding. So, we are using the HasData method to inform EF Core about the data it has to seed.
A . Net core project with Identity, Entity framework and language as C#. In Entity framework , we can define default database table values before creating database model. This concept is called seeding.
With seed data, you must specify the key. Otherwise it won't know which record to ensure is there. It is documented here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With