Removing all records from navigation properties in Entity Framework

坚强是说给别人听的谎言 提交于 2019-12-19 03:23:11

问题


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 started like this:

foreach(Student student in program.Students)
program.Students.Remove(student);

But I am a little bit skeptical about this.

Than I tried this way:

while (program.Students.Count > 0)
    program.Students.Remove(program.Students.ToList()[0]);

But this seems weird too.

Is there some simpler way to do this or if not which way is the best?


回答1:


I really don't know if it's gonna work or not, but I can not help it, I'm curious. Is program.Students.Clear() working? Or maybe reset it, reinitializing it? I hope it helped you...

Edit: Please use @Ladislav Mrnka's response, as that is the correct one. I have tried to remove the answer but I cannot because it's the accepted one




回答2:


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.




回答3:


.Clear() method is very good. It deletes all navigation properties in database. That's simple rather than foreach loop.



来源:https://stackoverflow.com/questions/6180927/removing-all-records-from-navigation-properties-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!