How can a single Entity Framework 7 database be used?
Now you will have to manually seed (however in the future it will talk about high level API ).
You can do it like this (assuming you are using ASP.NET 5) in a Configure
class method Startup
:
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 browse the Music Store app with its SampleData , which is a little more attractive and reliable.
source to share
In the function public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
in the class Startup
add this
if (env.IsDevelopment())
{
app.UseBrowserLink();
SeedData.InitializeDatabaseAsync(app.ApplicationServices).Wait();
}
And the implementation 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 link to these things is above at here . Hope for this help.
source to share