Code First Migration in ASP.Net Core
Generally we create database first and then we create data model classes in project, and while we publish application we need to take care about database creation and table.Code first, its approach that we first create data model classes and code itself create database and while publishing application, we don't need to take care about database and its tables, code automatically manage.
While executing code first migration command in .Net Core C#, we are facing some issues sometimes, here I faced some issues and found some solutions as below.
Issue 1
Getting error, while executing command
Add-Migration -Context "DatabaseContext"
Unable to create an object of type 'DatabaseContext'. Add an implementation of 'IDesignTimeDbContextFactory<DatabaseContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
Solution
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<DatabaseContext>
{
public DatabaseContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<DatabaseContext>();
var connectionString = configuration.GetConnectionString("dbConStr");
builder.UseSqlServer(connectionString);
return new DatabaseContext(builder.Options);
}
}
Issue 2
Getting error, while executing below command
Add-Migration -Name "Migration Name" -Context "DatabaseContext"
GenericArguments[0], 'SampleWebAPI.Migrations.DatabaseContext', on 'Microsoft.EntityFrameworkCore.Design.IDesignTimeDbContextFactory`1[TContext]' violates the constraint of type 'TContext'.
Solution
1. First remove migration folder (if any) from project which was created by above command
Issue 3
Getting error, while executing command
Update-Database
More than one DbContext was found. Specify which one to use. Use the '-Context' parameter for PowerShell commands and the '--context' parameter for dotnet commands.
Solution
Update-Database -Context "DatabaseContext"
Finally
Use below migration commands for .Net Core
1. Add-Migration -Name "Migration Name" -Context "DatabaseContext"
2. Update-Database -Context "DatabaseContext"
Enjoy !!!
:)