Entity Framework Code First approach in asp.net MVC with example

I hope you enjoy our last article Let's start with Entity Framework code first approach. From that article you will learn basic overview of what Entity Framework code first approach is and how it works?

Entity Framework simplify data access to working directly with database. No need to write extra code to handle all data interaction with database.No need to create datatables and Database manually Entity Framework will do it for you. Entity Framework is best suit for Asp.net MVC application. Most developers who are working in asp.net MVC always prefer Entity Framework for DB access.

In this article we create sample Entity Framework Code First example with asp.net MVC. Before going further if you are newbie to asp.net MVC please read out How to create Sample Project in asp.net MVC to start with basic.

Recommended to read
Note: We have just implement concept of Entity Framework code First Approach in asp.net MVC and not included any CRUD operation or Migration concept. We are going to implement same example as we implemented in our last article[^]. Please read our next articles regarding CRUD operation in Asp.net MVC using EF code first approach and Migration in Entity Framework code first approach.

1. Create empty MVC project.
2. As per we describe in our previous article[^] add Entity Framework reference to project. 
3. Add Student.cs, Department.cs and StudentDbContext.cs in model folder.
entity-framework-code-first-approach-in-asp.net-mvc

Student.cs
public class Student
{
    public Student()
    {

    }
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    [DataType(DataType.Date), 
     DisplayFormat(DataFormatString = "{0:dd/MM/yy}", 
     ApplyFormatInEditMode = true)]
    public DateTime? DateOfBirth { get; set; }
    public string EmailId { get; set; }
    public string Address { get; set; }
    public string City { get; set; }

    public Department Department { get; set; } // Navigation Property
}
Department.cs
public class Department
{
    public Department()
    {

    }
    [Key]
    public int Id { get; set; }
    public string DepartmentName { get; set; }

    public List Students { get; set; } // Navigation property
}
StudentDbContext.cs
public class StudentDbContext : DbContext
{
    public StudentDbContext ()
         : base("StudentDbContext")
    {
    }
    public DbSet<Student> Students { get; set; }
    public DbSet<Department> Departments { get; set; }
}
We add base("StudentDbContext") that will indicate your connectionString name.
4. Add connectionstring to web.config file.(Note: It will automatically create Database if you will not add any connectionstring in project.)
<connectionStrings>
  <add name="StudentDbContext"
       connectionString="server=Your Server Name; database=MVCEFcodeFirst; integrated security=true;"
       providerName="System.Data.SqlClient"/>
</connectionStrings>
5. Add HomeController.cs to Controllers folder.
public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        using(var context= new StudentDbContext())
        {
            var student = new Student()
            {
                Name = "Test",
                EmailId = "test@gmail.com",
                Address = "Test Address",
                City = "Test City"
            };
            context.Students.Add(student);
            context.SaveChanges();
        }
        return View();
    }
}
Database
Now, it's time to run project. EF code first creates database with name "MVCEFcodeFirst" as we declared in connectionstring.

Data which we added to student table,

Migrations
Please read our article migrations in Entity Framework Code First Approach.

Keep reading our blog for our next article CRUD operation in asp.net MVC EF code first approach.