2011-07-04 9 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に設定されている新しいコンテキストに添付された答えを...見つけることができたので、我々は、SAを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

関連する問題