2016-11-08 5 views
1

を追加した後、通常tipical EF6 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"の割り当ての直前の場合に、注入されたコンテキストでエラーがスローされる可能性がありますか?あなたはこのようにそれを行うことはできませんなぜ

答えて

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"; 
} 
+0

ザッツnewStudentは(はい、私のミスは私が "newStudent" と改名したために"student")は存在する可能性があり、存在する場合は "StudentName"だけを設定する必要はなく、他の20個のプロパティも設定する必要があります。 – Sauron

+0

最新の投稿をご覧ください。 – Sampath