3

Is there a proper way to seed a database?

I can't seem to find any document to accomplish this.

Dave Zych
  • 21,581
  • 7
  • 51
  • 66
Raphael
  • 91
  • 1
  • 3

2 Answers2

4

For now, you'll have to manually seed (however there is talk of a high level API for this in the future).

You can do that like this (assuming you're using ASP.NET 5) in the Configure method of the Startup class:

public class Startup
{
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger)
    {
        using (var context = (MyContext) app.ApplicationServices.GetService<MyContext>())
        {
            if (env.IsDevelopment())
            {
                //Add seed code here

                context.MyEntity.Add(new MyEntity{ Id = 1 });
                //etc

                context.SaveChanges();
            }
        }
    }
}

You can also review the Music Store sample application with it's SampleData class which is a little bit more involved and robust.

Dave Zych
  • 21,581
  • 7
  • 51
  • 66
-1

In the public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) function in the Startup class, add this

if (env.IsDevelopment())
{
    app.UseBrowserLink();
    SeedData.InitializeDatabaseAsync(app.ApplicationServices).Wait();
}

And the implementation of the SeedData.InitializeDatabaseAsync as below

public class SeedData
{
    public static async Task InitializeDatabaseAsync(IServiceProvider serviceProvider,
        bool createUsers = true)
    {
        using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var db = serviceScope.ServiceProvider.GetService<SampleDbContext>();
            await db.Database.MigrateAsync();
            using (db)
            {
                await InsertTestData(db);
            }
        }
    }

    private static async Task InsertTestData(SampleDbContextdbContext)
    {
        // seed data here
    }
}

The reference of those things above at here. Hope this help.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
thangchung
  • 2,020
  • 2
  • 17
  • 28