Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to validate property to be unique?

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);
    }

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading