Code First Migration in ASP.Net Core

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 !!!

:)

Code First Steps in ASP.Net C#

Code First Steps in ASP.Net C#

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.

Lets see, how to work with code first in .Net C#

Steps

1.First provide connection string in web.config file.
<connectionStrings>
    <add name="conDemoDB" connectionString="data source=ServerName; initial catalog=dbName; user id=username; password=password;" providerName="System.Data.EntityClient"/>
  </connectionStrings>

2. Create data model classes as per your requirement

3. Install Entity Framework using nu-get package installer or command 

4. Create DataContext Class

using System.Data.Entity;
using System.Data.Entity.Infrastructure;
 
namespace DemoApp.Reporsitory
{
    public class dataContext : DbContext
    {
        public dataContext()
            : base("name=conDemoDB")
        {
        }
 
        public virtual DbSet<Menu> Menus { get; set; }
        public virtual DbSet<MenuItem> MenuItems { get; set; }
    }
}


5. Open Package Manager Console from Tools -> NuGet Package Manager

1. Enable-Migrations  

2. Add-Migration "Comments"

3. Update-Database -Verbose 

Once command executes successfully, you can open database and check that tables are created.

for more detail, https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/automatic

Enjoy !!!

:)