Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to seed in Entity Framework Core 2?

I have two tables, and I want to fill them using seeds.

I use ASP.NET Core 2 in Ubuntu.

How to populate the data for the two tables where one is connected to the other via a foreign key?

The Flowmeter has many notes, and the note belongs to Flowmeter.

I want to do something like this, but it should be stored in the database:

new Flowmeter  {     Make = "Simple model name",     SerialNum = 45,      Model = "Lor Avon",      Notes = new List<Note>()     {         new Note() { Value = 45, CheckedAt = System.DateTime.Now },         new Note() { Value = 98, CheckedAt = System.DateTime.Now }     } } 
like image 899
zshanabek Avatar asked Jul 17 '17 15:07

zshanabek


People also ask

How do I Seed data in .NET core?

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. We are going to use seeding in order to define default users and roles here.

What is running Seed method in Entity Framework?

The Seed method takes the database context object as an input parameter, and the code in the method uses that object to add new entities to the database. To seed data into your database, you need to override the Seed method.

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

We can use the HasData method of the ModelBuilder to seed the initial data into the database via migrations.


1 Answers

As of Entity Framework Core 2.1 there is now a new method of seeding data. In your DbContext class override OnModelCreating:

protected override void OnModelCreating(ModelBuilder modelBuilder) {     modelBuilder.Entity<Blog>().HasData(new Blog { BlogId = 1, Url = "http://sample.com" }); } 

And for related entities, use anonymous classes and specify the foreign key of the related entity:

modelBuilder.Entity<Post>().HasData(     new {BlogId = 1, PostId = 1, Title = "First post", Content = "Test 1"},     new {BlogId = 1, PostId = 2, Title = "Second post", Content = "Test 2"}); 

Important: Please note you will need to run an add-migration after you enter this data in your OnModelCreating method and Update-Database to update your data.

The official docs have been updated.

like image 186
Blake Mumford Avatar answered Sep 19 '22 04:09

Blake Mumford