Code First Migration Using NuGet Commands In ASP.NET MVC 5

Datetime:2016-08-23 04:37:59          Topic: ASP.NET MVC           Share

In code first approach, classes are defined by the means of C# or VB code with properties, these classes will be generated into tables and properties are converted into columns by Entity Framework when executing code.

In this article we will implement code first migration approach using NuGet Commands.

Step By Step Walkthrough

Step 1

Go to Visual Studio 2013 and ASP.NET Web Application

Step 2

Add MVC Application

Add ConnectionString Web.Config File where you wish to create table.

<connectionStrings>  
    <add name="ConnectionStr" connectionString="Data Source=SHRIDHAR-PC; Initial Catalog=iShrissdb;User Id=*****;Password=********;" providerName="System.Data.SqlClient" />  
  </connectionStrings>  
Step 3

Now add a model class which you wanted to be created in the database.

Step 4

Here we named our class as UserInfo.

Step 5

Add another class file in model for creating table in the database.

Step 7

Declare attributes which you wanted as column in table.

Step 8

Now the time is to give the connectionstring and name of the table on second class file i.e, UserContext. Before you do this you have to add using System.Data.Entity  to inherit UserContext class with DbContext as in the following figure:

DBContext

Step 9

After this step, build the solution.

Step 10

Now go to ToolsNuGet Package Manager , then  Packet Manager Console

Run the following NuGet Commands.

Enable-Migrations  

This command basically creates Migration folder in the solution consisting of configuration class file.

Configuration file

In this file we can configure migrations of context.

Add-Migration and provide migration name

Add-Migration  

Update-Database -Verbose  

This command will bring the mentioned database to update and can check SQL for running migration.

Whole NuGet Command execution in Packet Manager Console is given in the following code snippet:

PM> Enable-Migrations  
Checking if the context targets an existing database...  
Code First Migrations enabled for project CodeFirstMigration.  
PM> Add-Migration  
cmdlet Add-Migration at command pipeline position 1  
Supply values for the following parameters:  
Name: UserContextss  
Scaffolding migration 'UserContextss'.  
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration UserContextss' again.  
PM> Update-Database -Verbose  
Using StartUp project 'CodeFirstMigration'.  
Using NuGet project 'CodeFirstMigration'.  
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.  
Target database is: 'iShrissdb' (DataSource: SHRIDHAR-PC, Provider: System.Data.SqlClient, Origin: Configuration).  
Applying explicit migrations: [201510141612178_UserContextss].  
Applying explicit migration: 201510141612178_UserContextss.  
CREATE TABLE [dbo].[UserInfoes] (  
    [Id] [int] NOT NULL IDENTITY,  
    [Name] [nvarchar](max),  
    [Age] [int] NOT NULL,  
    [Email] [nvarchar](max),  
    CONSTRAINT [PK_dbo.UserInfoes] PRIMARY KEY ([Id])  
)  
CREATE TABLE [dbo].[__MigrationHistory] (  
    [MigrationId] [nvarchar](150) NOT NULL,  
    [ContextKey] [nvarchar](300) NOT NULL,  
    [Model] [varbinary](max) NOT NULL,  
    [ProductVersion] [nvarchar](32) NOT NULL,  
    CONSTRAINT [PK_dbo.__MigrationHistory] PRIMARY KEY ([MigrationId], [ContextKey])  
)  
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])  
VALUES (N'201510141612178_UserContextss', N'CodeFirstMigration.Migrations.Configuration',  0x1F8B0800000000000400CD57DB6EDC36107D0FD07F10F8D400F6D29797D49012B86BBB309AB58DC8C93B579A9589F2A29094B1FB6D79C827F5173AD47D25EFCD358AC280B14BCE1C9E399C0BF7EF1F3FC34F4B29826730966B1591D3C9090940253AE52A8B48E116C71FC8A78FBFBC0BAF53B90CBE3576E7DE0E3D958DC89373F905A5367902C9EC44F2C468AB176E92684959AAE9D9C9C96FF4F494024210C40A82F04BA11C97507EC1AF53AD12C85DC1C44CA7206CBD8E3B71891ADC310936670944648A1637DC5837E399610EE94C2A27125C0ACE90500C624102A69476E5FEC5570BB1335A65718E0B4C3CAE7240BB051316EA302E3AF37D233A39F311D1CEB1814A0AEBB43C10F0F4BC96880EDD5F253469254411AF516CB7F251974246040531B76AA149303CEC622A8C37DCA2F3A4F13E0AC636476D8E602AF93F342A842B0C440A0A6798380A1E8AB9E0C99FB07AD47F818A5421449F2E12C6BDB5055C7A303A07E3565F605107719B9280AEFBD1A163EBD6F3A9C2BB55EEFC8C047778389B0B68B3A12745ECB4813F40018606E903730E8CF21850EA393A7D7096FFDF9C86E987054582195B7E0695B9A788E04712DCF025A4CD4ACDE0ABE2587FE8E44C01BB0EB9CC605744DB01AE25E3E28D6986B4CBB8711E62B13BC651D55E32FA3558BA17F21177EB94B4F551EBE1549831B8516A771CAA9630E9B65E22DBD2EA9A0FADBA4FD3A5E8863615CE589EA36EBDB655AF0471DDB38EE3C3AB58561834B12F1473CBB63D0993956530D8ED95F115736CCEFCCD4D533932EB5FC206819B93063A0F0BB593BD71F09F2BA7DD3D6508D7697983E149ACBC325268596D66523AC70913CCBCD005A65A14526DEA24DBBCABBAEEFB572BFB239445DB072817F6F7AF6BB68F502F8D31423AD06F785F747461839E3A4C806DB53334694F6F6B68502B619DB707CCFD26912B1312A038CF3CF5491CAFAC0339F10693F8BB980A8EF1760633A6F802ACABC60EC1997B367833FC7FE637B536157B0EF1FF7C7672AFEACEE978E020EA8F4BF5CC4CF2C4CCAF922DDFF7910E1C8925D17F33100F2072D8D01BB7E537186B554544249DE397C78A68B30BF6D5636F5CA221ED3FE0C32BB03CEB20FC735E41E273BF036D6C3C9746710CAFCFA831195CC80C1C4B51A54BE3F882250EB713B0B67CA87C63A228EF6C0EE9ADBA2F5C5EB84B6B41CEC5DAFB2CA4DBCF2F67FB3AE7F03EF7DFEC5B848034398600F7EAF7828BB4E57D334EC84D103E61EA6A4356F85043B86CD522DD69B527502DDF15E4A07CAD3E82CC0582D97B15B367780D37CCB1CF90B164D574DACD20BB2F625DF6F08A337C2A485B6374FEFE4729F5BF4A3FFE032F99C847C70E0000 , N'6.1.1-30610')  
  
Running Seed method.  

You can see two tables created on sql database namely _Migration history which stored entry of every migration in it and other table is UserInfoes consisting of provided column names.

Open the table UserInfoes , there is no data in the table.

Enter some dummy info UseInfoes table.

Now you can display this data in the list,

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  
using CodeFirstMigration.Models;  
  
namespace CodeFirstMigration.Controllers  
{  
    public class HomeController : Controller  
    {  
        UserContext UContext;  
        public HomeController()  
        {  
            UContext = new UserContext();  
        }  
        public ActionResult Index()  
        {  
            List<UserInfo> listuser = new List<UserInfo>();  
            listuser = UContext.UserInfo.ToList();  
            return View(listuser);  
              
        }  
}  
}  

Press F5

Closure.

In this article we learned code first migration using nuget command and Entity Framework in ASP.NET MVC 5 .

Happy coding!





About List