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 } } }
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.
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.
We can use the HasData method of the ModelBuilder to seed the initial data into the database via migrations.
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.
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