How to seed in Entity Framework Core 2?

2020-01-24 05:32发布

I have two tables and I want to fill it 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 foreign key?

The Flowmeter has many notes and 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 }
    }
}

8条回答
女痞
2楼-- · 2020-01-24 06:04

Create seed data static class like

 public static class SeedData
    {
        public static void Initialize(IServiceProvider serviceProvider)
        {
            var context = serviceProvider.GetRequiredService<YourDbContext>();
            context.Database.EnsureCreated();
            if (!context.Items.Any())
            {
                context.Items.Add(entity: new Item() { Name = "Green Thunder" });
                context.Items.Add(entity: new Item() { Name = "Berry Pomegranate" });
                context.Items.Add(entity: new Item() { Name = "Betty Crocker" });
                context.Items.Add(entity: new Item() { Name = "Pizza Crust Mix" });

                context.SaveChanges();
            }

            if (!context.Shoppings.Any()) {
                context.Shoppings.Add(entity:new Shopping() { Name="Defualt" });
            }
        }
    }

update your program.cs code for inserting your seed data like below

 public class Program
    {
        public static void Main(string[] args)
        {

            //CreateWebHostBuilder(args).Build().Run();
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context = services.GetRequiredService<YourDbContext>();
                    context.Database.Migrate(); // apply all migrations
                    SeedData.Initialize(services); // Insert default data
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
查看更多
ら.Afraid
3楼-- · 2020-01-24 06:06

In case somebody still interested in this topic, we've created a set of tools (a .net core global tool and a library) which simplifies the process of data seeding.

Long story short: you can save the content of your current DB to some JSON or XML files and then add to your app a few lines of code that loads those files and import the data saved there to your DB. The toolset is totally free and open-source.

The detailed step-by-step instructions are published here.

查看更多
登录 后发表回答