Removing All Entries from Navigation Properties in Entity Framework

I have a 1: N ratio between Program and Student tables, which EF converts to a navigation property. Now I want to delete all these entries in these students. I started like this:

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

But I am a little skeptical about this.

Than I tried this way:

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

But that also seems strange.

Is there any easier way to do this, or if not the best way?

+3
source share
3 answers

I really don't know if this will work or not, but I can’t help, I'm curious. Does it work program.Students.Clear()? Or maybe reset, reinitialization? Hope this helps you ...

: , @Ladislav Mrnka, . , ,

+11

, , - :

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

, FK null, . FK NULL, .

+20

.Clean () the method is very good. It removes all navigation properties in the database. This simple, not foreach loop.

+1
source

All Articles