How does one seed Entity Framework 7 database?

entity-framework-core

Question

Is there a proper way to seed a database?

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

Popular Answer

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.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why