无法将编辑后的数据保存到数据库中,返回NULL,我该如何解决?

时间:2017-12-14 11:12:07

标签: c# datagridview entity-framework-6 edit crud

Button2是编辑按钮,现在我应该编辑显示在文本框中的数据,然后按编辑更改值并保存到数据库中并在gridview中显示它们。但由于某种原因,它说newEmployee.FirstName为null,我该怎么办?

private void button2_Click(object sender, EventArgs e)
    {

        Employee Emp = SetValues(textBox1.Text, textBox2.Text, textBox3.Text);
        bool result = UpdateEmployee(Emp);
        ClearAll();
        Display();

    }

    public bool UpdateEmployee (Employee Emp) 
    {
        bool result = false;
        using (var entity = new NorthwindEntities())
        {               
            Employee newEmployee = entity.Employee.Where(x => x.EmployeeID == Emp.EmployeeID).Select(x => x).FirstOrDefault();
            newEmployee.FirstName = Emp.FirstName;
            newEmployee.LastName = Emp.LastName;
            newEmployee.BirthDate = Emp.BirthDate;                
            entity.SaveChanges();
            result = true;
        }
        return result;
    }

    private Employee SetValues(string FirstName, string LastName, string BirthDate)
    {
        Employee Emp = new Employee();
        Emp.FirstName = FirstName;
        Emp.LastName = LastName;
        Emp.BirthDate = BirthDate;
        return Emp;
    }

2 个答案:

答案 0 :(得分:0)

请执行employee检查,检查您是否收到null

Employee newEmployee = entity.Employee.Where(x => x.EmployeeID == 
  Emp.EmployeeID).Select(x => x).FirstOrDefault();
if(newEmployee!=null)
{          
  newEmployee.FirstName = Emp.FirstName;
  newEmployee.LastName = Emp.LastName;
  newEmployee.BirthDate = Emp.BirthDate;                
  entity.SaveChanges();
  result = true;
}

我认为你收到错误是因为FirstOrDefault返回空值,这是你没有检查

而不是FirstOrDefault您必须使用SingleOrDefault,因为只有一名员工要使用一个ID进行映射,因为我认为在大多数情况下它是主要值。并且你不会得到多于一个记录,即你只会收到单个记录。

您忘记将实体的状态设置为已修改状态:EntityState.Modified

using (var context = new BloggingContext()) 
{
    //set stus to modified  
    context.Entry(existingBlog).State = EntityState.Modified; 
    // Do some more work...  
    context.SaveChanges(); 
}

答案 1 :(得分:0)

简单的答案是

newEmployee.FirstName = Emp.FirstName ?? string.Empty;

那说我不知道​​为什么Emp.FirstName从零开始。在您的代码中,以下任何内容都没有意义

Employee newEmployee = entity.Employee.Where(x => x.EmployeeID == Emp.EmployeeID).Select(x => x).FirstOrDefault();

因为如果newEmployee是新的

,则不能拥有EmployeeID