I'm building a new project using ASP.net Core 2 and EntityFrameWorkCore 2.1.0 and I began to build the database structure. Now I have to make my first Migration to get my database ready and when I execute 'Add-Migration Init' into the Package Manager Console I got this error:
The current CSharpHelper cannot scaffold literals of type 'Microsoft.EntityFrameworkCore.Metadata.Internal.DirectConstructorBinding'. Configure your services to use one that can.
Also I tried this documentation https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations and the message I got is:
Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
I also followed this article without any success.
If I try without Microsoft.AspNetCore.Identity.EntityFrameworkCore 2.0.2 and with a simple 2 tables structure I'm able to make it work.
So now I need your help...
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:
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