Tuesday, August 5, 2014

Code First Approach Using Entity Framework in ASP.Net MVC 4

Code First Approach Using Entity Framework in ASP.Net MVC 4

In this blog, I am explaining the code first approach using entity framework in asp.net mvc 4.

Code First Approach creates the database automatically for you according to your model classes in the project, so don’t need a DBA to work on database, create it and then give it you to start the developing the project. Code First approach gives you the freedom to write the model classes according to your business logic and it will create the database automatically.

Step 1

First create an empty asp.net mvc 4 application and and install the Entity Framework 5 like this:



Open Package Manager Console:






Now add 3 model classes to the project like this:

Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CodeFirstMvcApp.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
        public DateTime EnrollmentDate { get; set; }

        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }
}

Enrollment.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CodeFirstMvcApp.Models
{
    public enum Grade
    {
        A, B, C, D, F
    }

    public class Enrollment
    {
        public int EnrollmentID { get; set; }
        public int CourseID { get; set; }
        public int StudentID { get; set; }
        public Grade? Grade { get; set; }

        public virtual Course Course { get; set; }
        public virtual Student Student { get; set; }
    }
}

Course.cs


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace CodeFirstMvcApp.Models
{
    public class Course
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }

        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }
}

Step 2

Now add a context class to the project named “StudentContext” like this:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace CodeFirstMvcApp.Models
{
    public class StudentContext : DbContext
    {
        public DbSet<Student> Students { get; set; }
        public DbSet<Enrollment> Enrollments { get; set; }
        public DbSet<Course> Courses { get; set; }
    }
}

Step 3

Now add a  controller named “HomeController” to the project like this:



In template – select the MVC Contoller with read/write actions and views  using Entity Framework

And in Model Class – Select the Student model class

And in Data Context class – Select the StudentContext Class which we have created earlier.

And click on Add button:

In Solution Explorer – you will see that five views have been created automatically in the Home under the View folder that are – Create, Details, Delete, Edit and Index





And there are some code automatically generated in HomeContoller like below :

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CodeFirstMvcApp.Models;

namespace CodeFirstMvcApp.Controllers
{
    public class HomeController : Controller
    {
        private StudentContext db = new StudentContext();

        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View(db.Students.ToList());
        }

        //
        // GET: /Home/Details/5

        public ActionResult Details(int id = 0)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        //
        // GET: /Home/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Home/Create

        [HttpPost]
        public ActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            {
                db.Students.Add(student);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(student);
        }

        //
        // GET: /Home/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        //
        // POST: /Home/Edit/5

        [HttpPost]
        public ActionResult Edit(Student student)
        {
            if (ModelState.IsValid)
            {
                db.Entry(student).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }

        //
        // GET: /Home/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        //
        // POST: /Home/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Student student = db.Students.Find(id);
            db.Students.Remove(student);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

Step 4

Now add the connection string in the web.config file like this:

<connectionStrings>
    <add name="StudentContext" connectionString="Data Source=DELL-PC;Initial Catalog=StudentDB;Integrated Security=true;" providerName="System.Data.SqlClient" />
  </connectionStrings>

As you can see, I have put the name of the connection string same to the name of our data context class StudentContext.

Step 5


Now run the application



Now click on Create New and add a new record like this:







Your data has been saved and each & every functionality is working that is you can create a new record, edit, delete and view the details and the list of records is also coming.

Now you can the stop the application and run again – as you can see that data is maintained and it is not saved locally but we haven’t created any database so where our data has been stored.

Now go to the server explorer in the View menu of the Visual Studio 2012 and you can see that the Entity Framework and the Code First Approach has created the database for you automatically.





You can also see you’re newly and automatically created database in the SQL Server 2008 like this:




Thank you for reading this article, please put your valuable comment or any suggestion/question in the comment box. 





No comments:

Post a Comment