2011-07-04 3 views
1

그것은 EntityFramework 내가 개체를 업데이트 할 얻을 수없는 몇 가지 이유 ... 여기ADO.Net EntityFramework 업데이트

내가 저장소 클래스 등을 사용하고있어

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(); 
     } 
    } 
} 

있어 사용하여 내 처음 이 ...

employee emp = EmployeeRepository.Select().FirstOrDefault(); 
emp.Username = "Imran"; 
EmployeeRepository.Update(emp); 

답변

2

분리 된 개체는 EntityState가 unchaged로 설정되어 새로운 컨텍스트에 첨부 된 대답을 ... 찾을 관리, 그래서 우리는 사를 caling 전에 수정으로 변경해야 문맥에 대한 veChanges() 메소드.

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(); 
    } 
} 

유용한 링크 ..

update disconnected object in entity framework

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