EntityFramework Core automatic migrations
Solution 1
You can call context.Database.Migrate()
in your Startup.cs
eg:
using (var context = new MyContext(...))
{
context.Database.Migrate();
}
Solution 2
EF core doesn't support automatic migrations
.So you have to do it manually.
From the perspective of automatic migrations as a feature, we are not planning to implement it in EF Core as experience has showed code-base migrations to be a more manageable approach.
You can read full story here : Not to implement Automatic Migrations
Solution 3
This is the way they do it in IdentityServer4 http://identityserver.io
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration.GetConnectionString("DefaultConnection");
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// this will do the initial DB population
InitializeDatabase(app);
}
private void InitializeDatabase(IApplicationBuilder app)
{
using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();
scope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
...
}
}
Solution 4
Automatic migrations is not supported in EF Core. Migration it is necessary to create hands. To automatically apply all existing handmade migrations need to add the following code in the class Program:
public class Program
{
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<MyDbContext>();
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>();
}
Solution 5
My working automigration code Asp Net Core 2.0.7.
// startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// configure app
SeedData.Initialize(app.ApplicationServices);
}
// dbInitializer.cs
public static class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var serviceScope = serviceProvider.CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
// auto migration
context.Database.Migrate();
// Seed the database.
InitializeUserAndRoles(context);
}
}
private static void InitializeUserAndRoles(ApplicationDbContext context)
{
// init user and roles
}
}
Related videos on Youtube
Lapenkov Vladimir
At work full stack developer .Net Core microservices plus front (Vue ,Angular + React course). Engaged in database development on MSSQL & Oracle. Since 2016 has developed some projects for Android. At home: Like to apend time with children, do some sport & travel.
Updated on July 09, 2022Comments
-
Lapenkov Vladimir almost 2 years
Is there any code to perform automatic migration in
Entity Framework core
code first
in asp.net core project?I do it simply in MVC4/5 by adding
Database.SetInitializer(new MigrateDatabaseToLatestVersion<AppDbContext, MyProject.Migrations.Configuration>()); public Configuration() { AutomaticMigrationsEnabled = true; }
This saves time when entities changed
-
Tseng over 7 yearsIt's called EntityFramework Core 1.0, thanks
-
-
Lapenkov Vladimir over 7 yearsMyContext looks this way , I don't know what to put in options public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
-
Frank Odoom over 7 yearsRefer to this article to see how you can manually configure your context stackoverflow.com/questions/38417051/… and github.com/aspnet/EntityFramework/issues/6493
-
Lapenkov Vladimir over 7 yearsI do the following way in Startup.cs : Startup::Configure after defining routes i add : var options = new DbContextOptionsBuilder<ApplicationDbContext>(); options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")); using (var context = new ApplicationDbContext(options.Options)) { context.Database.Migrate(); } but this doesn't perform migrations
-
Frank Odoom over 7 yearsRegister your context with dependency injection docs.efproject.net/en/latest/platforms/aspnetcore/new-db.html
-
Lapenkov Vladimir over 7 yearsI registered it this way : services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
-
Frank Odoom over 7 yearsdownload a simple sample from this repository..this uses Package Manager Console Scripts...hope it helps :-) github.com/dotnetjalps/EntityFrameworkCoreMigration
-
Arwin over 7 yearsBe that as it may, it worked perfectly for me in all the projects I worked on, resulting in extremely low-fuss maintenance especially during the build-up of a project. Shame that it is gone, but I can imagine sometimes the overhead wasn't worth it.
-
ProfK almost 7 yearsWhy are you using an array if you only access the element at 0?
-
Mentor almost 7 yearsin order to have one field for the lock and a quick check without unboxing.
-
Afshar Mohebi over 6 yearsStill no chance for automatic migrations to be supported in EF Core 2.0 in Sep. 2017?
-
Sampath over 6 yearsMaybe this helps: @Afshar github.com/aspnet/EntityFrameworkCore/issues/8045
-
Afshar Mohebi over 6 yearsThank you @Sampath, the link provides an alternative instead of automatic migrations, if I am understanding correctly. My team needs automatic migration in production enviroment rather than dev environment.
-
Sampath over 6 yearsOh..OK, Actually I'm not using this tech stack now due to now I'm working only on Ionic mobile apps.But according to my post's link, they labeled it as
closed-wont-fix
@Afshar -
Akash Kava over 6 years@FrankOdoom Answer is wrong, unless individual migration steps are added, Migration does not work and it is not equivalent of
AutomaticMigrationsEnabled
-
eka808 over 5 yearsWhen the model changes a lot and and multiple people work on the same project, migrations leads more problems than solutions. Moreover, having thousands of migrations makes the build slower and complicated for no reason. In this context, automatic migration seems the more reasonnable approach.
-
Rosdi Kasim over 4 yearsThey no longer do this. I have checked their source code.
-
Ali Dehghan Tarzeh over 4 years@Sampath What you consider as "Automatic Migrations" is not what is meant by this question. Here, what they mean is "to update the database on the production server on the first run of the application, whenever the developer makes a change to the data structure by creating and running a manual migration", which could be simply done (as is mentioned in other answers here), but the thing EF Core does not support, is, "to update the database automatically whenever there's a change in the data structure, without creating a manual migration". There's a big difference between the two!
-
Ali Dehghan Tarzeh over 4 yearsHere's a link to the full instructions for running the manually-created migrations on the server automatically: blog.rsuter.com/…
-
Sampath over 4 years@AliDehghanTarzeh Those are not official. See the official link: github.com/aspnet/EntityFrameworkCore/issues/6214
-
karunakar bhogyari about 4 yearscontext.Database.Migrate(); will update the database based on the migrations you have created.So do not forget to add migrations.
-
Gert Arnold almost 4 yearsProbably not tested before posting.
-
Daniel over 3 yearsThis is a duplicate of @Matt-Morgan's answer above. Although the timestamp of your original answer is 2017-02-17, you added the scoped dependency injected dbcontext solution in 2018-06-07, while Matt published the same answer 2017-04-20.
-
Johnny Oshika over 3 yearsThis technique works well for me. Thank you!
-
Naveen Kumar V about 3 yearsWorked for me :)
-
Jucko Thirteen almost 3 yearsAll the examples were for ASP .NET. But finally, this method works for C# 5 with EFCore. This took me hours to figure out...
-
kaptcha about 2 yearsCan this work with Postgres or just SQL Server?
-
Ionut N about 2 yearsThis package is designed to work only with Sql Server.