1

it's my first time using the EntityFramework and for some reason I cannot get an object to update...

Here's the

public static class EmployeeRepository
{
    public static List<employee> Select(int start = 0, int limit = 10)
    {
        using (var db = new MySqlEntities())
            return (from t in db.employees orderby t.ID select t).Skip(start).Take(limit).ToList();
    }

    public static List<employee> Search(string query, int limit = 10)
    {
        using (var db = new MySqlEntities())
            return (from t in db.employees where t.Name.StartsWith(query) || t.Username.StartsWith(query) select t).Take(limit).ToList();
    }

    public static void Update(employee Employee)
    {
        using(var db = new MySqlEntities())
        {
            db.employees.Attach(Employee);
            /* 
               Edit:
               also tried adding (line below) here
               db.ApplyCurrentValues<employee>(db.employees.EntitySet.Name, Employee);
            */
            db.SaveChanges();
        }
    }
}

I'm using the repository class like this...

employee emp = EmployeeRepository.Select().FirstOrDefault();
emp.Username = "Imran";
EmployeeRepository.Update(emp);
Saad Imran.
  • 4,480
  • 2
  • 23
  • 33

1 Answers1

2

Managed to find the answer...When a detached entity is attached to a new context the EntityState is set to unchaged, so we have to change it to modified before caling the SaveChanges() method on the context.

public static void Update(employee Employee)
{
    using(var db = new MySqlEntities())
    {
        db.employees.Attach(Employee);
        db.employees.Context.ObjectStateManager.ChangeObjectState(Employee, System.Data.EntityState.Modified);
        db.SaveChanges();
    }
}

Helpful Links..

update disconnected object in entity framework

http://blogs.msdn.com/b/dsimmons/archive/2009/11/09/attachasmodified-revisited.aspx

Community
  • 1
  • 1
Saad Imran.
  • 4,480
  • 2
  • 23
  • 33