In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how to configure Entity Framework Core seed data Data-Seeding". In daily operation, I believe many people have doubts about how to configure Entity Framework Core seed data Data-Seeding. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to configure Entity Framework Core seed data Data-Seeding". Next, please follow the editor to study!
What is Data-Seeding
Data-Seeding is a new addition to EntityFrameworkCore 2.1or later. At the beginning of a project, we often need to initialize some basic data to the database, which can be achieved through the Data-Seeding feature. In this article, we will explain how to initialize data.
2. Initialization method
The specific data initialization methods are as follows:
Configuration in the model. This is done by calling the HasData () method.
Added when manual migration.
Custom initialization logic.
Let's explain how to use these three methods for data migration.
1. Configuration in the model
This is done by calling the HasData () method. This is also what I often use in the process of project development. This way is to override the OnModelCreating () method in the data context class. Let's first look at the definition of the HasData () method:
As you can see, the parameters of the method can be an array of type Blog, as shown in the following code:
Using EFCore.Model;using Microsoft.EntityFrameworkCore;namespace EFCore.Data {/ data context / public class EFDbContext:DbContext {protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder) {optionsBuilder.UseSqlServer ("Data Source=.;Initial Catalog=EFTest;User ID=sa;Password=123456;");} public DbSet Blogs {get; set } / override the OnModelCreating method / protected override void OnModelCreating (ModelBuilder modelBuilder) {/ / add seed data modelBuilder.Entity () for Blog entities. HasData (new Blog () {/ / Id field to be assigned Otherwise, Id=1, Name= "ef core"}, new Blog () {Id=2, Name= "ASP.NET Core"} will be reported. New Blog () {Id=3, Name= "graphical data structure"}) Base.OnModelCreating (modelBuilder);}
We notice that Id is automatically set as the primary key by default and grows automatically. But here you want to set the value of Id, even if Id is an automatically generated primary key, otherwise the error shown in the following figure will be reported:
After adding the seed data, we run the program to view the output:
View the database:
The database and table are generated, and there is initialization data in the table.
If we want to add a piece of data at this time, the code is as follows:
Using EFCore.Model;using Microsoft.EntityFrameworkCore;namespace EFCore.Data {/ data context / public class EFDbContext:DbContext {protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder) {optionsBuilder.UseSqlServer ("Data Source=.;Initial Catalog=EFTest;User ID=sa;Password=123456;");} public DbSet Blogs {get; set } / override the OnModelCreating method / protected override void OnModelCreating (ModelBuilder modelBuilder) {/ / add seed data modelBuilder.Entity () for Blog entities. HasData (new Blog () {/ / Id field to be assigned Otherwise, Id=1, Name= "ef core"}, new Blog () {Id=2, Name= "ASP.NET Core"} will be reported. New Blog () {Id=3, Name= "schematic data structure"}, / / add a new data new Blog () {Id=4 Name= "C# Advanced programming"}) Base.OnModelCreating (modelBuilder);}
Can we still use the same method at this time? We are now running the program to see the results:
At this time, the execution of the program failed, and the data in the table did not increase. This means that the context.Database.EnsureCreated () method is valid only the first time it is executed, and then becomes invalid when the data is changed. So is there any way to achieve it? At this point, only the migration from the command line or the migration class generated by the context.Database.Migrate method call will be valid for the changes to the data.
We delete the database just generated, comment out the newly added data, and then use the command line migration to generate the database table. First, add the migration:
Then update the database:
After updating the database, we add a piece of data to the HasData () method, and then execute the above command to add migration and update the database again, and find that the new data will be added to the database at this time.
After executing the second add migration command, if you do not use the update database command, you can also migrate by code, which is to invoke the context.Database.Migrate command as follows:
Using EFCore.Data;using Microsoft.EntityFrameworkCore;using System;namespace EFCore.Con {class Program {static void Main (string [] args) {Console.WriteLine ("Hello World!"); EFDbContext dbContext = new EFDbContext (); / / migrate dbContext.Database.Migrate (); / / bool tfTrue = dbContext.Database.EnsureCreated () / / if (tfTrue) / / {/ / Console.WriteLine ("Database created successfully!"); / /} / / else / / {/ / Console.WriteLine ("Database creation failed!"); / /} Console.ReadKey ();}}
The latest migration file is automatically invoked to update the database.
Note: changes to data that are called by this method will only take effect at the time of migration, that is, only migration classes generated through command migration or context.Database.Migrate method calls will be valid for data changes. The call to the context.Database.EnsureCreated () method is valid only when it is executed for the first time, but the data will not be valid when the data is changed.
There are two limitations to this approach:
You must specify a value for the primary key (even if the primary key is automatically generated by the database).
The added data must be static, without any dependencies. For example, the value of the added Id primary key is not allowed if it is referenced in other tables.
2. Add when manual migration
This method is not explained here, and those who are interested can refer to the official documentation of Microsoft.
3. Custom initialization logic
A simple and effective way to perform data seeding is to use DbContext.SaveChanges () before the main application logic starts execution. The code is as follows:
Using EFCore.Data;using EFCore.Model;using Microsoft.EntityFrameworkCore;using System;using System.Linq;namespace EFCore.Con {class Program {static void Main (string [] args) {Console.WriteLine ("Hello World!"); / / EFDbContext dbContext = new EFDbContext (); / migrate / / dbContext.Database.Migrate () / bool tfTrue = dbContext.Database.EnsureCreated (); / if (tfTrue) / {/ Console.WriteLine ("Database created successfully!") / else / {/ Console.WriteLine ("Database creation failed!"); /} # region uses custom initialization logic using (EFDbContext context=new EFDbContext ()) {context.Database.EnsureCreated () Var testBlog = context.Blogs.FirstOrDefault (p = > p.Name = = "C #"); if (testBlog = = null) {/ / add data context.Blogs.Add (new Blog () {Name = "C #"}) } / / Save data context.SaveChanges ();} # endregion Console.ReadKey ();}
Seed data can also be added through this custom logic. If seed data is added to the HasData () method, the seed data in the HasData () method is first added to the database. If there is no data named C#, another piece of data will be added.
If you have this data, it will not be added.
Note: when adding data in this way, you can no longer assign a value to the primary key Id, because if you create a database, you will automatically set Id as the primary key and assign a value automatically when you add data.
III. The essence of Data-Seeding
When the HasData () method is first migrated, it is essentially a call to the InsertData method in the MigrationBuilder class to insert.
When you call the HasData () method to change the data (without changing the primary key), you are essentially calling the UpdateData method in the MigrationBuilder class for the update operation.
When you call the HasData () method to remove data or change the primary key, you are essentially calling the DeleteData method in the MigrationBuilder class to delete or delete and update.
1. First migration
After we execute the add migration command for the first time, we generate a migration file, as shown in the following figure:
You can see that this is the InsertData method that is called to add data.
2. Modify data that is not a primary key
We modify the data to change ef core to ef core 3.1.1, as shown in the following figure:
After the modification, we execute the migration command, as shown in the figure:
At this point, you are going to look at the generated migration file:
At this point, the UpdateData method is executed.
3. Delete data
Then we comment out the simulation delete operation in the code with Id 1, and execute the migration command:
Looking at the generated migration file:
You can see that this is the DeleteData method that is executed.
4. Modify primary key data
We are changing the data with Id 2 to 6:
Performing a migration:
View the generated migration file:
This time the DeleteData method is executed first, and then the InsertData method is executed.
At this point, the study on "how to configure Entity Framework Core seed data Data-Seeding" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.