保存更改不保存

时间:2018-07-04 01:55:46

标签: c# entity-framework

具有以下代码-

'

当我调用saveChanges方法时,数据库中什么也没发生,为什么?我希望每个员工的工资增加12%,但是在数据库中什么都没有发生

1 个答案:

答案 0 :(得分:4)

好的,您的问题是您实际上没有更改实体。很难看到您想做什么,但是,这可能会推动您前进。

Select在这里不合适。相反,只需过滤您的员工​​即可:

var employees = context.Employees.Where(e => 
                      e.Department.Name == "Engineering" || 
                      e.Department.Name == "Tool Design" || 
                      e.Department.Name == "Marketing" || 
                      e.Department.Name == "Information Services");

// you need to modify each employee
foreach(var employee in employees)
{   
     // not sure this is correct, add pepper and salt to taste 
     employee.Salary = employee.Salary * 12 / 100 + e.Salary;
}

// then you can save
context.SaveChanges();

// List of infos
var listofInfo =  employees.OrderBy(e => e.FirstName)
                    .ThenBy(e => e.LastName)
                    .Select(e => $"{e.FirstName} {e.LastName} (${e.Salary:F2})")
                    .ToList();

foreach(var item in listofInfo)
   Console.WriteLine(item);