Problem
If I have 2 or more students trying to register for the last remaining seat available for a classroom lesson and they save simultaneously, entering my RegisterStudent()
controller method, the only certainty I have that the parent (YogabandEvent
) entity property MaxSize
will be maintained is when I fetch the parent, and I check the number of registrants already added is < MaxSize
and if true, I add the new registrant.
But I have a concurrency problem where if 2+ students have fetched the parent (YogabandEvent
) entity at the same time, getting a MaxSize
of 9, and then add a new registrant I could end up with more than MaxSize
(ex. 11+). So I have a concurrency issue!
Currently, I can either fetch the parent entity including the children (Registrants
) add the new child (Registrant
) to the parent and save or just insert a new Registrant
entity into the Registrant
table directly. But with either scenario, I could end up with a situation, stated above, where more students than the MaxSize
are registered.
Question
How can I restrict the child (Registrant
) entities to the MaxSize
in the parent (YogabandEvent
) entity using EF Core?
Here is my code - some properties left out for verbosity:
public class YogabandEvent : BaseEntity
{
public YogabandEvent()
{
Registrants = new List<Registrant>();
}
public DateTime Date { get; set; }
public DateTime DateUtc { get; set; }
public MaxSize MaxSize { get; set; }
public ICollection<Registrant> Registrants { get; set; }
}
public class Registrant : BaseEntity
{
public RegistrantType RegistrantType { get; set; }
public int UserId { get; set; }
public User User { get; set; }
public int EventId { get; set; }
public YogabandEvent Event { get; set; }
}
public enum MaxSize
{
Five = 5,
Ten = 10,
Fifteen = 15,
Twenty = 20,
ThirtyFive = 35
}