I am writing my simple MVC application using C#, SQLite and Entity Framework. I am having repository
Code snippet
public class MyRepository
{
public TeamContext _teamContext;
public MyRepository(TeamContext teamContext)
{
_teamContext = teamContext;
}
public void AddTeam(Team team)
{
team.Id = Guid.NewGuid();
_teamContext.Team.Add(team);
}
}
My requirement is that team names should be unique – there cannot be more than two teams with the same name. Using entity framework I would like to validate that but I am having logical issues. How can I validate that?
>Solution :
You can check if there is another record with the same name. If yes, then you need to throw an exception. Otherwise, continue the flow.
public void AddTeam(Team team)
{
if(_textContext.Team.Any(t => t.Name == team.Name))
{
throw new TeamAlreadyExists(team.Name);
}
team.Id = Guid.NewGuid();
_teamContext.Team.Add(team);
}
I suggest you to do the check from an upper level, like services, to keep the repository’s method as clean as possible.
Addition to this, it is recommended to use unique constraint on the database side as well, since it’s thread-safe and it protects from editing team’s name from other places.