I'm having a bit of trouble trying to add an object to the database using LINQ to SQL.
I have three tables in my database:
--------------------------------------------
tblShows
--------------------------------------------
ShowID | Name
--------------------------------------------
--------------------------------------------
tblShowEvents
--------------------------------------------
ShowEventID | ShowID | Name
--------------------------------------------
--------------------------------------------
tblShowEventAttendees
--------------------------------------------
ShowEventAttendeeID | ShowEventID | Name
--------------------------------------------
A Show has many Events, and each Event has many Attendees.
I have a page where I'm creating a Show. On the page, I'm adding Events to the Show, and Attendees to each Event, and then saving the show all at once.
Here is my code:
Show show = new Show();
show.Name = txtName.Text.Trim();
//add ShowEvents to Show
//showEventsList is a variable containing a List of ShowEvents
foreach (ShowEvent ev in showEventsList)
{
show.ShowEvents.Add(new ShowEvent
{
ShowID = show.ShowID,
Name = ev.Name
});
}
//Add ShowEventAttendees to each ShowEvent
//attendeesList is a variable containing a List of ShowEventAttendees
foreach (ShowEvent ev in show.ShowEvents)
{
foreach (ShowEventAttendee attendee in attendeesList)
{
ev.ShowEventAttendees.Add(new ShowEventAttendee
{
ShowEventID = ev.ShowEventID,
Name = attendee.Name
});
}
}
AppDataContext.DataContext.Shows.InsertOnSubmit(show);
AppDataContext.DataContext.SubmitChanges();
The issue occurs in the second foreach loop. If I take it out, the Show and ShowEvents get added to the database correctly.
What's the issue here?
EDIT for Jay:
I've tried this now:
AppDataContext.DataContext.Shows.InsertOnSubmit(show);
AppDataContext.DataContext.SubmitChanges();
//Add ShowEventAttendees to each ShowEvent
//attendeesList is a variable containing a List of ShowEventAttendees
foreach (ShowEvent ev in show.ShowEvents)
{
foreach (ShowEventAttendee attendee in attendeesList)
{
ev.ShowEventAttendees.Add(new ShowEventAttendee
{
ShowEventID = ev.ShowEventID,
Name = attendee.Name
});
}
}
AppDataContext.DataContext.SubmitChanges(); //trying to update, error here
But I get the same error on that last line. Going through the debugger, ShowEventID is no longer 0, but I'm getting the same error.