Let's specify some class named "Student
Class" in models folder has the Following Properties:
Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace MVC_Basic_Application.Models
{
public class Student
{
[Key]
public int StudentId
{ get; set; }
[Required(ErrorMessage
= "Please Enter FirstName")]
[StringLength(10, ErrorMessage = "FirstName
morethan 10 charcs")]
public string FirstName
{ get; set; }
[Required(ErrorMessage
= "Please Enter LastName")]
[StringLength(10, ErrorMessage = "LastName
morethan 10 charcs")]
public string LastName
{ get; set; }
[Range(5,
50, ErrorMessage = "Age Should Be Between 5 and 50")]
public int Age
{ get; set; }
[Required(ErrorMessage
= "Please Enter Location")]
[StringLength(10, ErrorMessage = "Location
morethan 10 charcs")]
public string Location
{ get; set; }
}
}
And My DataContext Class in models folder:
StudentStateEntities.cs is Specified
StudentStateEntities.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MVC_Basic_Application.Models
{
public class StudentStateEntities:DbContext
{
public DbSet<Student>
Students { get; set;
}
}
}
And Now I will get chance to analyse what to do when My requirement changes and how to handle my application logic and database simultaneously. The Answer arises to this question which helps to another model class name "StudentStateIntializer" where we inherit from base class DropCreateDatabaseIfModelChanges<> , This Class help to drop and recreate the database if the requirement changes as per the application basis with necessary properties specified in Student class.
So the Fully Completed
StudentStateIntializer.cs looks like this:
StudentStateIntializer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MVC_Basic_Application.Models
{
public class StudentStateIntializer:DropCreateDatabaseIfModelChanges<StudentStateEntities>
{
protected override void Seed(StudentStateEntities context)
{
var stu = new List<Student>
{
new Student
{
StudentId=1,
FirstName="Vijay",
LastName="Prativadi",
Location="Banglore",
Age=25
},
new Student
{
StudentId=2,
FirstName="Uday",
LastName="Prativadi",
Location="Mumbai",
Age=28
}
};
stu.ForEach(p=>context.Students.Add(p));
}
}
}
Before you render changes to the webbroswer just go to global.asax.cs
Add this line in Application_Start() of global.asax.cs file:
Database.SetInitializer<StudentStateEntities>(new StudentStateIntializer());
The Completed Code of global.asax.cs looks
like this:
Global.asax.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Data.Entity;
using MVC_Basic_Application.Models;





Join the conversation! Your thoughts help the community grow.