Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 951
ViqMontana Avatar asked Feb 21 '19 15:02

ViqMontana


People also ask

How do you seed data in a database?

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.

Which method can be used to seed initial data in database using Entity Framework Core?

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.

What is seed in .NET core?

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.


1 Answers

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

like image 140
Daniel A. White Avatar answered Oct 19 '22 21:10

Daniel A. White