EF6添加后编辑模型数据

时间:2016-11-08 14:35:55

标签: entity-framework entity-framework-6 add

通常,典型的EF6添加应该是

var newStudent = new Student();
newStudent.StudentName = "Bill";
context.Students.Add(newStudent);
context.SaveChanges();

在我的情况下,我正在使用这个逻辑

var student = context.Students.Find(id);
if (student == null)
{
    student = new Student();
    context.Students.Add(student );
}
student.blabla1 = "...";
student.blabla2 = "...";
//other 20 blabla...
student.StudentName = "Bill"; // StudentName is a required field
context.SaveChanges();

在实体框架6上添加方法后编辑数据模型是一个不好的做法?注入上下文可能会抛出一个错误,因为在另一个方法上调用了savechanges,而我的实际线程就在分配“StudentName”之前?

1 个答案:

答案 0 :(得分:0)

为什么你不能这样做......

   var student = context.Students.Find(id);

   if (student == null)
    {
        student = new Student();
        ModifyBlabla(student );//call private method
        context.Students.Add(student);
    }
  else
   {
     ModifyBlabla(student );//call private method
   }

    context.SaveChanges();

编辑方法:

private void ModifyBlabla(Student student)
{
   student.blabla1 = "...";
   student.blabla2 = "...";
   //other 20 blabla...
   student.StudentName = "Bill";
}