I have an entity called Entry connected to multiple TimeWindows. I want to clear all time windows, then add new ones. At first I tried:
target.TimeWindows.Clear();
but this didn’t really delete them, and only tried to remove the relationship, which caused an exception since there is foreign key from TimeWindows to Entry. Then I thought I should do this:
foreach (var tw in target.TimeWindows)
context.DeleteObject(tw);
but this throw an exception as well, since the collection was modified inside the foreach statement. So I thought of this:
while (target.TimeWindows.Count > 0)
context.DeleteObject(target.TimeWindows.Last());
But now I am a bit concerned about using Count property, because it might cause a SQL SELECT COUNT statement to be executed. Does it? If yes, how can I delete all time windows in Entity Framework?
Calling count on navigation property will cause select only if lazy loading is enabled and the property is not loaded yet. So the first call can cause something like:
and all count evaluations will just execute on loaded data.
You can also use this to avoid the second exception:
Or you can change your database and model to support identifying relation (FK to parent will became part of TimeWindow’s PK) and in such case your first code snippet will work.