I have an object Concert, which has a collection of Tickets.
Each Ticket has a TicketOption.
I am trying to save the Concert to the database using EF Core. It works if the Ticket collection is null and it worked until I added the TicketOptions to the tickets. Now I am getting errors related to tracking of the TicketOptions.
So previously I had
public override void Save(ConcertEvent concertEvent)
{
using (var _context = _contextFactory.CreateConcertDataContext())
{
_context.Update(concertEvent);
if (concertEvent.Business != null) { _context.Entry(concertEvent.Business).State = EntityState.Unchanged; }
if (concertEvent.Venue != null) { _context.Entry(concertEvent.Venue).State = EntityState.Unchanged; }
_context.SaveChanges();
}
}
When I added TicketOptions this started failing at _context.Update(concertEvent);
To try to fix the issue with TicketOptions I added the following:
public override void Save(ConcertEvent concertEvent)
{
using (var _context = _contextFactory.CreateConcertDataContext())
{
if (concertEvent.Tickets != null)
{
var uniqueTicketOptions = concertEvent.Tickets
.Where(t => t.TicketOption != null)
.Select(t => t.TicketOption);
.GroupBy(to => to!.Id)
.Select(g => g.First());
foreach (var t in uniqueTicketOptions)
{
_context.Entry(t!).State = EntityState.Unchanged;
}
}
_context.Update(concertEvent);
if (concertEvent.Business != null) { _context.Entry(concertEvent.Business).State = EntityState.Unchanged; }
if (concertEvent.Venue != null) { _context.Entry(concertEvent.Venue).State = EntityState.Unchanged; }
_context.SaveChanges();
}
}
This still fails at _context.Update(concertEvent);
The same applies to Business and Venue, both of which should not be saved/updated and simply setting the EntityState to Unchanged worked perfectly here so I am unsure why it doesn’t work with TicketOptions.
Note – Both Tickets can reference the same or different TicketOptions.