ADO.Net EntityFramework更新

时间:2011-07-04 23:33:11

标签: c# wpf entity-framework

这是我第一次使用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);

1 个答案:

答案 0 :(得分:2)

管理以找到答案...当一个分离的实体附加到新的上下文时,EntityState被设置为unchaged,因此我们必须在对上下文中的SaveChanges()方法进行调用之前将其更改为已修改。

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