Friday, 10 February 2017

Basic CRUD operation using Entity Framework

Basic set up follow this:

Environment setup sample here

Model Class:
public class Employee
    {

       public Employee()
       {

       }

       [Key]
       public int EmpID { get; set; }
       public string EmpName { get; set; }
       public string Address { get; set; }
    }

Context Class:


    public class MyContext : DbContext
    {

       public MyContext()
            : base("dbConnectionName")
       {
           Database.SetInitializer<MyContext>(new CreateDatabaseIfNotExists<MyContext>());
           
       }

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

    }


Controller:

 MyContext context = new MyContext();
//Add
            Employee emp = new Employee() { EmpID = 1, EmpName = "Arul", Address = "Cbe" };
            context.Employees.Add(emp);

            context.SaveChanges();

//Edit
  Employee emp = new Employee() { EmpID = 1, EmpName = "Kumar", Address = "Chennai" };
            context.Entry(emp).State= EntityState.Modified;

            context.SaveChanges();

//Delete
  Employee emp = context.Employee .Find(1);
                if (emp == null)
                {
                    return HttpNotFound();
                }
                context.Employee .Remove(emp );
                 context.SaveChanges();

//Read
List<Employee >empList=context.Employee.select(x=>x.EmpID ,x.EmpName ,x.Address).ToList();





No comments:

Post a Comment