Code First Migration - ASP.NET Core MVC 6 With EntityFrameWork Core

Introduction
 
In this article, we are going to explain Code First Migration in ASP.NET Core MVC 6 with EntityFrameWork Core, using Command Line Interface ( CLI ).
 
Before reading this article, you must read the articles given below for ASP.NET Core knowledge.
Model Class
 
We are going to create a sample Code First Migration project in ASP.NET Core 1.0. Model class given below contains the properties of the user details in our Applications.
  1. using System;  
  2.    
  3. namespace CodeFirstMigration.Models  
  4. {  
  5.     public class UserDetails  
  6.     {  
  7.         public Guid Id { getset; }  
  8.    
  9.         public string Name { getset; }  
  10.    
  11.         public string EmailId { getset; }  
  12.    
  13.         public string Company { getset; }  
  14.     }  
  15. }  
LocalDB Configuration in ASP.NET Core 1.0
 
In the previous versions, everything is handled by Web.Config but in ASP.NET Core, the connection string is written in appsettings.json file. By default, it will show as a LocalDB path and as per our requirement, we can change the connection string path.
 
In the way given below, we can create connection string in ASP.NET Core 1.0.
 
Picture Source : https://rajeeshmenoth.wordpress.com 
 
The appsetting JSON file contains the LocalDB connection string details in our Application and we have given the database name as “UserDb”. If you want to know more about JSON file configuration in ASP.NET Core, please check our previous article Adding A Configuration Source File In ASP.NET Core 1.0.
  1. {  
  2.   "ConnectionStrings": {  
  3.     "DefaultConnection""Server=(localdb)\\MSSQLLocalDB;Database=UserDb;Trusted_Connection=True;MultipleActiveResultSets=true"  
  4.   }  
  5. }  
DbContext in ASP.NET Core 1.0
 
The code givden below contains the information about EntityFrameWork Core DbContext. We can add the LocalDB connection string details with the help of "UseSqlServer" Method.
  1. using Microsoft.EntityFrameworkCore;  
  2. using Microsoft.Extensions.Configuration;  
  3.    
  4. namespace CodeFirstMigration.Models  
  5. {  
  6.     public class CodeDbContext : DbContext  
  7.     {  
  8.         private IConfigurationRoot _config;  
  9.    
  10.         public CodeDbContext(IConfigurationRoot config, DbContextOptions options) : base(options)  
  11.         {  
  12.             _config = config;  
  13.         }  
  14.    
  15.         public DbSet<UserDetails> userDetails { getset; }  
  16.    
  17.         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  18.         {  
  19.             base.OnConfiguring(optionsBuilder);  
  20.    
  21.             optionsBuilder.UseSqlServer(_config["ConnectionStrings:DefaultConnection"]);  
  22.         }  
  23.     }  
  24. }  
Seed Data in EntityFrameWork Core
 
We are going to implement Code First Migrations in Entity Framework Core to seed the database with test data and manually we are entering the seed data information in the “CodeDbSeedData” class. The code given below contains the default values of User Details Table in our Application.
  1. using System;  
  2. using System.Linq;  
  3. using System.Threading.Tasks;  
  4.    
  5. namespace CodeFirstMigration.Models  
  6. {  
  7.     public class CodeDbSeedData  
  8.     {  
  9.         private CodeDbContext _context;  
  10.    
  11.         public CodeDbSeedData(CodeDbContext context)  
  12.         {  
  13.             _context = context;  
  14.         }  
  15.    
  16.         public async Task SeedData()  
  17.         {  
  18.             if (!_context.userDetails.Any())  
  19.             {  
  20.                 var user = new UserDetails()  
  21.                 {  
  22.                     Id = Guid.NewGuid(),  
  23.                     Name = "RajeeshMenoth",  
  24.                     EmailId = "[email protected]",  
  25.                     Company = "HappiestMinds Technologies Pvt Ltd"  
  26.                 };  
  27.    
  28.                 _context.userDetails.Add(user);  
  29.                 await _context.SaveChangesAsync();  
  30.             }  
  31.         }  
  32.     }  
  33. }  
project.json
 
project.json contain the complete picture of dependency in our Applications.
  1. {  
  2.   "dependencies": {  
  3.     "Microsoft.NETCore.App": {  
  4.       "version""1.0.1",  
  5.       "type""platform"  
  6.     },  
  7.     "Microsoft.AspNetCore.Diagnostics""1.0.0",  
  8.     "Microsoft.AspNetCore.Server.IISIntegration""1.0.0",  
  9.     "Microsoft.AspNetCore.Server.Kestrel""1.0.1",  
  10.     "Microsoft.Extensions.Logging.Console""1.0.0",  
  11.     "Microsoft.AspNetCore.Mvc.Core""1.1.1",  
  12.     "Microsoft.EntityFrameworkCore""1.1.0",  
  13.     "Microsoft.EntityFrameworkCore.SqlServer""1.1.0",  
  14.     "Microsoft.AspNetCore.Mvc""1.1.0",  
  15.     "Microsoft.Extensions.Configuration.FileExtensions""1.1.0",  
  16.     "Microsoft.Extensions.Configuration.Json""1.1.0",  
  17.     "Microsoft.EntityFrameworkCore.Design""1.0.0-preview2-final"  
  18.   },  
  19.    
  20.   "tools": {  
  21.     "Microsoft.AspNetCore.Server.IISIntegration.Tools""1.0.0-preview2-final",  
  22.     "Microsoft.EntityFrameworkCore.Tools": {  
  23.       "version""1.0.0-preview2-final",  
  24.       "imports": [  
  25.         "portable-net45+win8+dnxcore50",  
  26.         "portable-net45+win8"  
  27.       ]  
  28.     }  
  29.   },  
  30.    
  31.   "frameworks": {  
  32.     "netcoreapp1.0": {  
  33.       "imports": [  
  34.         "dotnet5.6",  
  35.         "portable-net45+win8"  
  36.       ]  
  37.     }  
  38.   },  
  39.    
  40.   "buildOptions": {  
  41.     "emitEntryPoint"true,  
  42.     "preserveCompilationContext"true  
  43.   },  
  44.    
  45.   "runtimeOptions": {  
  46.     "configProperties": {  
  47.       "System.GC.Server"true  
  48.     }  
  49.   },  
  50.    
  51.   "publishOptions": {  
  52.     "include": [  
  53.       "wwwroot",  
  54.       "web.config"  
  55.     ]  
  56.   },  
  57.    
  58.   "scripts": {  
  59.     "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]  
  60.   }  
  61. }  
Startup.cs
 
The class given blow contains the complete middleware details in our Applications.
  1. using CodeFirstMigration.Models;  
  2. using Microsoft.AspNetCore.Builder;  
  3. using Microsoft.AspNetCore.Hosting;  
  4. using Microsoft.AspNetCore.Http;  
  5. using Microsoft.Extensions.Configuration;  
  6. using Microsoft.Extensions.DependencyInjection;  
  7. using Microsoft.Extensions.Logging;  
  8. using System;  
  9.    
  10. namespace CodeFirstMigration  
  11. {  
  12.     public class Startup  
  13.     {  
  14.         private IConfigurationRoot _config;  
  15.    
  16.         public Startup(IHostingEnvironment env)  
  17.         {  
  18.             var ConfigBuilder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)  
  19.                         .AddJsonFile("appsettings.json");  
  20.             _config = ConfigBuilder.Build();  
  21.         }  
  22.         // This method gets called by the runtime. Use this method to add services to the container.  
  23.         // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940  
  24.         public void ConfigureServices(IServiceCollection services)  
  25.         {  
  26.             services.AddSingleton(_config);  
  27.             services.AddDbContext<CodeDbContext>();  
  28.             services.AddTransient<CodeDbSeedData>();  
  29.             services.AddMvc();  
  30.         }  
  31.    
  32.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  33.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,  
  34.             CodeDbSeedData seeder)  
  35.         {  
  36.             loggerFactory.AddConsole();  
  37.    
  38.             if (env.IsDevelopment())  
  39.             {  
  40.                 app.UseDeveloperExceptionPage();  
  41.             }  
  42.    
  43.             app.UseMvc();  
  44.    
  45.             app.Run(async (context) =>  
  46.             {  
  47.                 await context.Response.WriteAsync(" Welcome to Dotnet Core !!");  
  48.             });  
  49.    
  50.             try  
  51.             {  
  52.                 seeder.SeedData().Wait();  
  53.             }  
  54.             catch (Exception ex)  
  55.             {  
  56.    
  57.                 throw ex;  
  58.             }  
  59.               
  60.    
  61.    
  62.         }  
  63.     }  
  64. }  
Code First Migration
 
The steps given below will explain the step by step Code First Migration in EntityFrameWork Core.
 
Setting Project Location
 
The command given below will help to change our current "C Drive" to "F Drive" because currently our Code First Migration project is saved into "F Drive".
 
Picture Source : https://rajeeshmenoth.wordpress.com
 
Dotnet ef-help command
 
The command given below will display for more information about dotnet ef command.
 
"dotnet ef –help"
 
 Picture Source : https://rajeeshmenoth.wordpress.com 
 
Starting With new migration
 
We are going to start with new EntityFrameWork migration, using the command given below.
 
"dotnet ef migrations add IntialDB"
 
 
Picture Source : https://rajeeshmenoth.wordpress.com
 
Update the database 
 
The command given below will update the EntityFrameWork Core database in ASP.NET Core Application.
 
"dotnet ef database update"
 
Picture Source : https://rajeeshmenoth.wordpress.com
 
Project Structure After Migration
 
The structure given below will be created after the ef migration in .NET Core.

 
Picture Source : https://rajeeshmenoth.wordpress.com
 
Local Db Created
 
The Dotnet EntityFrameWork CLI ( Command Line Interface ) creates the Local DB as "UserDB". Go to "View" and select "SQL Server Object Explorer" in Visual Studio. Now, expand "SQL Server -> (localdb) -> Databases -> UserDB".
 
Picture Source : https://rajeeshmenoth.wordpress.com
 
Output
 
 
Picture Source : https://rajeeshmenoth.wordpress.com
 
Reference
Conclusion
 
We learned about Code First Migration in ASP.NET Core MVC 6 with EntityFrameWork Core, using Command Line Interface ( CLI ) and I hope you liked this article. Please share your valuable suggestions and feedback.