ADO.NET Entity Framework Code First Development

I liked LINQ to SQL for its clean approach of defining only code to be able to access the database. ADO.NET Entity Framework comes with a much more richer experience of you being the fine grained control over the code. In this current version we have Model First and Database First approaches, now we have Code First.

You need to install the ADO.NET Entity Framework Code First API from Microsoft. I will let you Bing it. After that assume that you have two tables Department and Employee. One Department can have many employees.

You need the EntityFramework assembly to be part of your reference. You also need ComponentModel.DataAnnotations. Your department and employee class would look like,

 
 using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

/// <summary>
/// Department class
/// </summary>
public class Department
{
    [Key] //To make it Primary Key and Identity
    public int DeptId { get; set; }
    public string DeptName { get; set; }

    //Create Employee navigation property for Lazy Loading (1:many)
    public virtual ICollection<Employee> Employees { get; set; }
}

/// <summary>
/// Employee class
/// </summary>
public class Employee
{
    [Key] //To make it Primary Key and Identity
    public int EmpId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int DeptId { get; set; }

    //Create Department navigation property for Lazy Loading
    public virtual Department Department { get; set; }
}

After that you need the context class to create the connection

 public class EmpDeptContext : DbContext
{
    public DbSet<Employee> Emps { get; set; }
    public DbSet<Department> Depts { get; set; }
}

After that you write your application to add Departments and Employees and this will automatically create a database first at you localhost\sqlexpress (if no option provided), then enter the data into it.

 var deptSoftware = new Department() { DeptName = "Software" };
var deptIT = new Department() { DeptName = "IT" };

using(var db = new EmpDeptContext())
{
    new List<Employee> 
    {
        new Employee(){FirstName = "Wriju", LastName = "Ghosh", Department = deptSoftware},
        new Employee(){FirstName = "Saswati", LastName = "Sanyal", Department = deptSoftware},
        new Employee(){FirstName = "Wrishika", LastName = "Ghosh", Department = deptSoftware},
        new Employee(){FirstName = "Writam", LastName = "Ghosh", Department = deptIT},
        new Employee(){FirstName = "Debajyoti", LastName = "Ghosh", Department = deptIT},
        new Employee(){FirstName = "Sumitra", LastName = "Ghosh", Department = deptIT}
    }.ForEach(e => db.Emps.Add(e));
    int records = db.SaveChanges();
    Console.WriteLine("{0} record(s) saved", records);
}

That’s it!!! Isn’t it clean? No Edmx no extra resources.

Namoskar!!!