Thursday, December 29, 2016

Code First Migrations in MVC 5

Hi, In this Post I will show how to do Code First Migration in MVC 5.

Previously I had shown how to use Jquery DataTable in MVC and Asp.Net

MVC:
Asp.Net:

Create a New Project in Visual Studio 2015.
Go to Package Manager Console and enter the command as shown
  

enable-migrations













Now in the Package Manager Console use the below command
  

add-migration InitialModel
Migrations Folder is created in solution Explorer
Go to models folder and open IdentityModel, in ApplicationDbContext Class write BbSet as shown

public DbSet<Customer> Customers { get; set; }
public DbSet<Book> Books { get; set; }
Create Classes in Models Folder for Customer & Book as shown below

public class Customer
{
 public int Id { get; set; }
 public string Name { get; set; }
}

public class Book
{
 public int Id { get; set; }
 public string Name { get; set; }
}
Now go to Package Manager Console and use the below command
  

add-migration InitialMode –force
To Generate DB go to Package Manager Console enter below command
  

Update-database
Change Customer Model Class:

Add a New Property to the Customer Class as IsNewsLetterSubscribed .
Now go to Package Manager Console and use the below command to migrate
  

add-migration ADDIsNewsLetterSubscribed
To Generate DB go to Package Manager Console enter below command
  

Update-database
Add a New Class as MembershipTypes
Add reference to Customer Class as shown below.
  

public class MembershipType
{
 public int Id { get; set; }
 public int SignUpFee { get; set; }
 public int Duration { get; set; }
 public int Discount { get; set; }
}

public class Customer
{
 public int Id { get; set; }
 public string Name { get; set; }
 public bool IsNewsLetterSubscribed { get; set; }
 public MembershipType MembershipType { get; set; }
 public int MembershipTypeID { get; set; }
}
go to Package Manager Console

add-migration AddIsNewsLetterSubscribePlus
To Generate DB go to Package Manager Console enter below command
  

Update-database
Insert Default Data for MembershipTypes Table as follows:
  
In the Package Manager

add-migration Populate MembershipTypes
write SQL Queries as below
To Generate DB go to Package Manager Console enter below command
  

Update-database

Overriding Property Types with DataAnnotations:
  

[Required]
[StringLength(255)]
public string Name { get; set; }

To Generate DB go to Package Manager Console enter below command one by one
  

add-migration AddDataAnnotations
Update-database


Download the Entire Code from HERE

No comments:

Post a Comment