I have this code:
Schedule s = _entities.Schedules.Where(x => x.ScheduleID == schedule.ScheduleID && x.BookingObject.BookingObjectID == bookingObjectID).FirstOrDefault();
if(s == null)
s = new Schedule();
s.ScheduleStart = schedule.ScheduleStart;
s.ScheduleEnd = schedule.ScheduleEnd;
foreach (var t in schedule.Timetables)
{
s.Timetables.Add(t);
}
_entities.AddToSchedules(s);
_entities.SaveChanges();
Exception: System.InvalidOperationException
the object schedule gets passed in as a parameter
EDIT:
changed to:
Schedule sh = new Schedule();
sh.ScheduleStart = schedule.ScheduleStart;
sh.ScheduleEnd = schedule.ScheduleEnd;
foreach (var t in schedule.Timetables)
{
//sh.Timetables.Add(t); // doesn't work
sh.Timetables.Add(new Timetable { DayOfWeek = t.DayOfWeek, StartTime = t.StartTime, EndTime = t.EndTime }); // works
}
_entities.AddToSchedules(sh);
_entities.SaveChanges();
is there some logical reason why sh.Timetables.Add(t) doesn’t work since its a collection of Timetable?
/M
UPDATE: Just confirmed that this is likely to be the reason. And created a new tip in my tips series to explain.
I can think of one possible reason.Is the relationship between
schedule.Timetablesone to many? I.e. Can a timetable only be assigned to one schedule at a time?If so, this is failing:
Because as you add the ‘t’ to a different schedule, it is automatically removed from the old
schedule.Timetablescollection, which of course modifies the collection you are enumerating, which is a no-no.If so, the solution is simply to do something like this:
Here you enumerate the collection, before you start modifying it.