开发者

ADO.Net EntityFramework Update

开发者 https://www.devze.com 2023-03-17 10:59 出处:网络
it\'s my first time using the EntityFramework and for some reason I cannot get an object to update...

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)
    {
  开发者_C百科      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);


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

0

精彩评论

暂无评论...
验证码 换一张
取 消