Removing all records from navigation properties in Entity Framework

后端 未结 3 676
时光取名叫无心
时光取名叫无心 2021-01-05 13:57

I have 1:N relationship between Program and Student tables which EF converted into navigation property. Now I want to delete all those records in this navigation students. I

3条回答
  •  广开言路
    2021-01-05 14:25

    Unless you have very special association called identifying relation between your program and students you should use something like this:

    foreach(var student in program.Students.ToList())
    {
        program.Students.Remove(student); // Break realation
        context.Students.DeleteObject(student); // Delete student
    }
    

    Removing student from the navigation property will only set FK in the student to null but the record will not be deleted. If FK is not nullable you will get an exception.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题