简体   繁体   中英

WPF MVVM Changes to DataContext not saved to DB

I Have a data context containing a list of employees. My edit screen (dialog) is bound to the selected employee. When I edit the employee I can see the details changing in the main window employee listbox, so the employee object in the main list is being updated.

The dialog is setup to trigger a re-query of the Employee list in the datacontext after a successful call to _context.SaveChanges(). When the data comes back from the DB, none of the new values were saved.

It may be worth mentioning that the add employee function works perfectly.

Business context save method:

public Employee UpdateEmployee(Employee emp)
{
    if (emp == null)
       throw new ArgumentNullException("Employee", "Employee must be not null");

    Employee temp = _context.Employees.Find(emp.Id);
    _context.Employees.Attach(temp);
    temp = emp;

    _context.SaveChanges();
    return emp;
}

The temp employee object and attach command was a desperation move, yielding the same results.

Your code as written fetches the employee as it is in the data store , and saves it to temp . It then attaches this to the context (which it should already be anyway). It then attempts to save any changes made to temp - but none have been made.

Shouldn't you be attaching the actual entity you want to update, in this case emp ?

public Employee UpdateEmployee(Employee emp)
{
    if (emp == null)
       throw new ArgumentNullException("Employee", "Employee must be not null");

    _context.Employees.Attach(emp);
    _context.SaveChanges();

    return emp;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM