I have these entities in my business:
class Team
{
public int Id { get; set; }
public string Name { get; set; }
public List<Member> Members { get; set; }
}
class Member
{
public int TeamId { get; set; }
public int UserId { get; set; }
}
The business rule is that a team cannot have more than 10 members.
So you can add a constraint in your controller or handler like this:
AddTeamMemberHandler.cs
:
var team = dbContext.Teams
.Include(x => x.Members)
.FirstOrDefault(x => x.Id == 123);
if (team.Members.Count >= 10)
throw new Exception("Cannot add more members");
However, when you have multiple users trying to add users at the same time, and the current number of members in the team is 9, all of the request will pass the validation. This can lead to the number of members in the team exceeding 10.
I think it is possible to add a custom SQL constraint in the EF model configuration like this:
modelBuilder.Entity<Team>()
.HasCheckConstraint("Team_MaxMembers", $"COUNT(\"Members\") <= 10");
But I'm a little bit hesitant to add the business logic validation in the database layer as the constraint can be dynamic depending on the type of the team or the business rule has changed.
Another solution I can think of is using optimistic concurrency control and adding a concurrency token on team. This can prevent multiples users trying to add members at the same time.
Is there a different way to mitigate this sort of issue?
Thanks