I use entity framework core 2. I saw posts in stack-overflow but I can't resolve my problem. I want to use auto migration in my project without console command.
-
What you said about automatic migration is to use code to generate migration files and update to the database instead of using the command line, right?– Xueli ChenOct 29, 2019 at 5:41
-
exactly, I want when I change my model and run my code database changes automatically– ssmmooOct 29, 2019 at 6:13
Add a comment
|
1 Answer
Try this code:
using (var serviceScope = _scopeFactory.CreateScope())
{
using (var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>())
{
context.Database.Migrate();
}
}
Complete code:
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
host.Services.InitializeDb();
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{//Add Code }
}
}
public interface IDbInitializer
{
void Initialize();
}
public class DbInitializer : IDbInitializer
{
private readonly IServiceScopeFactory _scopeFactory;
public DbInitializer(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
public void Initialize()
{
using (var serviceScope = _scopeFactory.CreateScope())
{
using (var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>())
{
context.Database.Migrate();
}
}
}
}
public static class DbContextOptionsExtensions
{
public static void InitializeDb(this IServiceProvider serviceProvider)
{
var scopeFactory = serviceProvider.GetRequiredService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
{
var dbInitialize = scope.ServiceProvider.GetRequiredService<IDbInitializer>();
dbInitialize.Initialize();
}
}
}
-
tnx bro! but when i give my context to here : public void Initialize() { using (var serviceScope = _scopeFactory.CreateScope()) { using (var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>()) { context.Database.Migrate(); } } } i don't have Migrate()– ssmmooOct 28, 2019 at 13:05
-
2@ssmmoo, add
using Microsoft.EntityFrameworkCore
assembly reference . Oct 29, 2019 at 3:15 -
1tnx ali, i think it solves my problem, but it's not what i want completely, i'm so gratefull :)– ssmmooOct 31, 2019 at 15:03