Entity Framework - Update Single Entity

Steps to update entity. 

1. Retrive the existing employee information from database.
2. Modify the employee information out of Context scope (disconnected mode).
3. Pass the modified entity into the Entry method to get its DBEntityEntry object and set its state as Modified.
4. Call SaveChanges() method to update employee information into the database.

Employee emp;
//1. Employee information
using (var ctx = new EFSourceDBEntities())
    emp = ctx.Employees.Where(s => s.EmpId == 11).FirstOrDefault<Employee>();

//2. Update employee information
if (emp != null)
    emp.Name = "New Employee";

//save modified entity using new Context
using (var Ctx = new EFSourceDBEntities())
    //3. Set entity status as modified
    Ctx.Entry(emp).State = System.Data.Entity.EntityState.Modified;     
    //4. Call SaveChanges method to save changes in database

Praesent mattis

Pellentesque viverra vulputate enim. Aliquam erat volutpat. Pellentesque tristique ante ut risus. Quisque dictum. Integer nisl risus, sagittis convallis, rutrum id, elementum congue, nibh. Suspendisse dictum porta lectus. Donec placerat odio vel elit.

Read More