Sunday 31 January 2016

Entity framework code first example


A simple example of code first approach in entity frame work.

1.       Take the reference of entity frame work from Nugget Package and install it.



2.       Create a simple POCO class like below for Entity framework code first example
Like I have created two classes like below;
/// <summary>
    ///  Maintaning the employee details
    /// </summary>
    public class Employee
    {
        public Employee()
        {

        }
        public int EmployeeID { get; set; }
        public string Name { get; set; }
        public DateTime DateOfBirth { get; set; }
        public string Address { get; set; }
        public string PhoneNo { get; set; }
    }


    /// <summary>
    ///  Maintaning the Department details
    /// </summary>
    public class Department
    {
        public Department()
        {
        }

        public int DepartmentID { get; set; }
        public string DepartmentName { get; set; }
        public ICollection<Employee> Employees { get; set; }
    }

3.       Now need to create the tables for your POCO classes, use below code for creating tables using

///    /// <summary>
    ///  Creting tables by DbContext
    /// </summary>
    public class CompanyContext : DbContext
    {
        public CompanyContext()
            : base("Data Source=REETPC;Initial Catalog=CompanyDetails;Persist Security Info=True;User ID=sa;Password=password1")
        {

        }

        public DbSet<Employee> Employees { get; set; }
        public DbSet<Department> Departments { get; set; }

    }

4.       Code to call the DBContext as  like below;

class Program
    {
        static void Main(string[] args)
        {
            using (var ctx = new CompanyContext())
            {

                Employee em = new Employee() { EmployeeID =  1, Name ="Satya" };

                ctx.Employees.Add(em);
                ctx.SaveChanges();
            }
        }
    }

5.       Now where is the Tables have created now you can check the Database which ever you have given as connection string.
You can see the tables and records inserted into database as;




No comments:

Post a Comment