Tuesday, May 8, 2012

Entity Framework Model First Approach using MVC3

If you don't yet have a database, you can begin by creating a model using the Entity Framework designer in Visual Studio. When the model is finished, the designer can generate DDL (data definition language) statements to create the database. This approach also uses an .edmx file to store model and mapping information. The What's New in the Entity Framework 4 tutorial includes a brief example of Model First development.

 Create Models:   
 --------------------------------------------------------------------------------------------------------------------  
 namespace MVCWeb.Models  
 {  
   public class Student  
   {  
     public int StudentID { get; set; }  
     public string LastName { get; set; }  
     public string FirstMidName { get; set; }  
     public DateTime EnrollmentDate { get; set; }  
     public virtual ICollection<Enrollment> Enrollments { get; set; }  
   }  
 }  
 ---------------------------------------------------------------------------------------------------------------  
 namespace MVCWeb.Models  
 {  
   public class Enrollment  
   {  
     public int EnrollmentID { get; set; }  
     public int CourseID { get; set; }  
     public int StudentID { get; set; }  
     public decimal? Grade { get; set; }  
     public virtual Course Course { get; set; }  
     public virtual Student Student { get; set; }  
   }  
 }  
 ---------------------------------------------------------------------------------------------------------------  
 namespace MVCWeb.Models  
 {  
   public class Course  
   {  
     public int CourseID { get; set; }  
     public string Title { get; set; }  
     public int Credits { get; set; }  
     public virtual ICollection<Enrollment> Enrollments { get; set; }  
   }  
 }  
 --------------------------------------------------------------------------------------------------------------  
 Create DAL Folder and in that Create 2 Following Files  
 --------------------------------------------------------------------------------------------------------------  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Data.Entity;  
 using MVCWeb.Models;  
 using System.Data.Entity.ModelConfiguration.Conventions;  
 namespace MVCWeb.DAL  
 {  
   public class SchoolContext:DbContext  
   {  
     public DbSet<Student> Students { get; set; }  
     public DbSet<Enrollment> Enrollments { get; set; }  
     public DbSet<Course> Courses { get; set; }  
     protected override void OnModelCreating(DbModelBuilder modelBuilder)  
     {  
       modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();  
     }  
   }  
 }  
 -------------------------------------------------------------------------------------------------------------  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Data.Entity;  
 using MVCWeb.Models;  
 namespace MVCWeb.DAL  
 {  
   public class SchoolInitializer : DropCreateDatabaseIfModelChanges<SchoolContext>  
   {  
     protected override void Seed(SchoolContext context)  
     {  
       var students = new List<Student>  
       {  
         new Student { FirstMidName = "Carson",  LastName = "Alexander", EnrollmentDate = DateTime.Parse("2005-09-01") },  
         new Student { FirstMidName = "Meredith", LastName = "Alonso",  EnrollmentDate = DateTime.Parse("2002-09-01") },  
         new Student { FirstMidName = "Arturo",  LastName = "Anand",   EnrollmentDate = DateTime.Parse("2003-09-01") },  
         new Student { FirstMidName = "Gytis",  LastName = "Barzdukas", EnrollmentDate = DateTime.Parse("2002-09-01") },  
         new Student { FirstMidName = "Yan",   LastName = "Li",    EnrollmentDate = DateTime.Parse("2002-09-01") },  
         new Student { FirstMidName = "Peggy",  LastName = "Justice",  EnrollmentDate = DateTime.Parse("2001-09-01") },  
         new Student { FirstMidName = "Laura",  LastName = "Norman",  EnrollmentDate = DateTime.Parse("2003-09-01") },  
         new Student { FirstMidName = "Nino",   LastName = "Olivetto", EnrollmentDate = DateTime.Parse("2005-09-01") }  
       };  
       students.ForEach(s => context.Students.Add(s));  
       context.SaveChanges();  
       var courses = new List<Course>  
       {  
         new Course { Title = "Chemistry",   Credits = 3, },  
         new Course { Title = "Microeconomics", Credits = 3, },  
         new Course { Title = "Macroeconomics", Credits = 3, },  
         new Course { Title = "Calculus",    Credits = 4, },  
         new Course { Title = "Trigonometry",  Credits = 4, },  
         new Course { Title = "Composition",  Credits = 3, },  
         new Course { Title = "Literature",   Credits = 4, }  
       };  
       courses.ForEach(s => context.Courses.Add(s));  
       context.SaveChanges();  
       var enrollments = new List<Enrollment>  
       {  
         new Enrollment { StudentID = 1, CourseID = 1, Grade = 1 },  
         new Enrollment { StudentID = 1, CourseID = 2, Grade = 3 },  
         new Enrollment { StudentID = 1, CourseID = 3, Grade = 1 },  
         new Enrollment { StudentID = 2, CourseID = 4, Grade = 2 },  
         new Enrollment { StudentID = 2, CourseID = 5, Grade = 4 },  
         new Enrollment { StudentID = 2, CourseID = 6, Grade = 4 },  
         new Enrollment { StudentID = 3, CourseID = 1      },  
         new Enrollment { StudentID = 4, CourseID = 1,      },  
         new Enrollment { StudentID = 4, CourseID = 2, Grade = 4 },  
         new Enrollment { StudentID = 5, CourseID = 3, Grade = 3 },  
         new Enrollment { StudentID = 6, CourseID = 4      },  
         new Enrollment { StudentID = 7, CourseID = 5, Grade = 2 },  
       };  
       enrollments.ForEach(s => context.Enrollments.Add(s));  
       context.SaveChanges();  
     }  
   }  
 }  
 --------------------------------------------------------------------------------------------------------------  
 In Global.asax add the following on application Start  
 Database.SetInitializer<SchoolContext>(new SchoolInitializer());  
 -------------------------------------------------------------------------------------------------------------  
 Add Connection String in Web.config  
  <add name="SchoolContext" connectionString="data source=[ServerName];initial catalog=[DBName];integrated security=True;" providerName="System.Data.SqlClient"/>  
 -------------------------------------------------------------------------------------------------------------  
 Create a controller class, I have created the controller class for student  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Mvc;  
 using MVCWeb.DAL;  
 namespace MVCWeb.Controllers  
 {  
   public class StudentController : Controller  
   {  
     private SchoolContext db = new SchoolContext();  
     //  
     // GET: /Student/  
     public ActionResult Index()  
     {  
       return View(db.Students.ToList());  
     }  
   }  
 }  
 ---------------------------------------------------------------------------------------------------------------  
 Create the Index View for the same  
 @model IEnumerable<MVCWeb.Models.Student>  
 @{  
   ViewBag.Title = "Index";  
 }  
 <h2>Index</h2>  
 <p>  
   @Html.ActionLink("Create New", "Create")  
 </p>  
 <table>  
   <tr>  
     <th></th>  
     <th>  
       LastName  
     </th>  
     <th>  
       FirstMidName  
     </th>  
     <th>  
       EnrollmentDate  
     </th>  
   </tr>  
 @foreach (var item in Model) {  
   <tr>  
     <td>  
       @Html.ActionLink("Edit", "Edit", new { id=item.StudentID }) |  
       @Html.ActionLink("Details", "Details", new { id=item.StudentID }) |  
       @Html.ActionLink("Delete", "Delete", new { id=item.StudentID })  
     </td>  
     <td>  
       @item.LastName  
     </td>  
     <td>  
       @item.FirstMidName  
     </td>  
     <td>  
       @String.Format("{0:g}", item.EnrollmentDate)  
     </td>  
   </tr>  
 }  
 </table>  



run the code and call Student/index it will create the database for you and add the data provided in the SchoolInitializer Class to respective tables.

No comments:

Post a Comment