How to Create Migrations After Upgrading to ASP.NET Core 2.0

Unable to create migrations after upgrading to ASP.NET Core 2.0

You can add a class that implements IDesignTimeDbContextFactory inside of your Web project.

Here is the sample code:

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<CodingBlastDbContext>
{
public CodingBlastDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<CodingBlastDbContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new CodingBlastDbContext(builder.Options);
}
}

Then, navigate to your Database project and run the following from command line:

dotnet ef migrations add InitialMigration -s ../Web/

dotnet ef database update -s ../Web/

-s stands for startup project and ../Web/ is the location of my web/startup project.

resource

Cannot add migration with ASP.net Core 2

I found some reasons why we can get hard time to use migration with the latest version of ASP.net Core 2 at this time.

First of all, if you just migrate from an old project which is not built from ASP.net Core at all, you will have to add a Context Factory to make Migrations work. Here my own Context Factory:

public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
builder.UseSqlServer("Server=(local)\\SQLEXPRESS;Database=yourdatabase;User ID=user;Password=password;TrustServerCertificate=True;Trusted_Connection=False;Connection Timeout=30;Integrated Security=False;Persist Security Info=False;Encrypt=True;MultipleActiveResultSets=True;",
optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(ApplicationDbContext).GetTypeInfo().Assembly.GetName().Name));

return new ApplicationDbContext(builder.Options);
}
}

If you divided your project into layers for architecture purpose, add the Context Factory inside the Repository Layer or in the same library where your DbContext is.

Secondly, before any attempt to add a migration, you must set the selection of “set as startup project” on the repository library or where your DbContext is.
Then, those are the packages you need to use for migration:

  • Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Design
  • Microsoft.EntityFrameworkCore.SqlServer

That’s all!

Be careful when you add other packages because they can break the Migration system. As an example, if you use a Unit of Work & Repositories Framework like URF and install URF.Core.EF.Trackable -Version 1.0.0-rc2, you will no longer be able to add migration. Instead use URF.Core.EF.Trackable -Version 1.0.0-rc1. I guess this can happen with many other packages as well.

Finally, read this article will be helpful. It’s a little outdate but it can help people out there.

Cheers

Run EF migrations on Startup in asp.net core 6 application

Try below:

var app = builder.Build();

// omitted

using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;

var context = services.GetRequiredService<MyContext>();
context.Database.Migrate();
}

// omitted

app.Run();

Entity Framework Core 2.0 add-migration not generating anything

@JulieLerman provided the answer when I asked in her pluralsight course discussion. There is apparently an issue with attempting this with the .NET Core class libraries. The successful workaround is to put the following in the csproj file of the DBContext project:

<PropertyGroup>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConf‌igurationFiles>
</PropertyGroup>

She wrote a blog about it:
http://thedatafarm.com/data-access/the-secret-to-running-ef-core-2-0-migrations-from-a-net-core-or-net-standard-class-library/

Additionally, be sure to set the project with the DBContext in it as the startup project

Can't create EF migrations after installing .NET 6

I had this problem recently after upgrading to .NET6.

The solution for me was to follow the link in the error message and install Microsoft.NETCore.App 2.0.0.

https://dotnet.microsoft.com/download/dotnet/2.0/runtime

I'm guessing that the upgrade to 6 removed this framework as it is considered legacy ... BUT ... is still used (or marked as a required dependency somehow) in the dot net tools.

Why does dotnet ef migrations add start my application?

I also met this problem. I use ASP.Net Core 6 WebApi with full controllers.

I saw march's comment on a GitHub issue (Migrations script not using IDesignTimeDbContextFactory), which gave me inspiration.

So, I changed WebHost.CreateDefaultBuilder(args)(obsolete in .NET6) to Host.CreateDefaultBuilder(args) in Program.cs and now the problem is solved. Unfortunately, I still don't know the specific causes of the problem.

"dotnet ef migrations add" will still start application but Host will throw a StopTheHostException to stop the ASP.NET Core Host and then will create migration related files successfully which likes

Build started...
Build succeeded.
[16:46:18 INF] Configuring web host (Identity.API)...
[16:46:18 FTL] Program terminated unexpectedly (Identity.API)!
Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException: Exception of type 'Microsoft.Extensions.Hosting.HostFactoryResolver+HostingListener+StopTheHostException' was thrown.
at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.OnNext(KeyValuePair`2 value)
at System.Diagnostics.DiagnosticListener.Write(String name, Object value)
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at Program.<<Main>$>g__CreateHostBuilder|0_0(IConfiguration configuration, String[] args) in G:\ASPNETCore\HongJieSun.Innermost\Services\Innermost.Identity\Innermost.Identity.API\Program.cs:line 47
at Program.<Main>$(String[] args) in G:\ASPNETCore\HongJieSun.Innermost\Services\Innermost.Identity\Innermost.Identity.API\Program.cs:line 11
To undo this action, use Remove-Migration.


Related Topics



Leave a reply



Submit