Home > Mobile >  How to validate property to be unique?
How to validate property to be unique?

Time:11-15

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?

CodePudding user response:

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.

CodePudding user response:

use UNIQUE constraint that ensures all values in a column or a group of columns are distinct from one another or unique. for example :

CREATE TABLE contacts(
    contact_id INTEGER PRIMARY KEY,
    first_name TEXT,
    last_name TEXT,
    email TEXT NOT NULL UNIQUE
);

if you insert duplicate value in email,you get an error as follow:

Error while executing SQL query on database 'xxx': UNIQUE constraint failed: contacts.email

also you can set multi column unique:

CREATE TABLE tbaleName(
   ...
    UNIQUE(columnName_1,columnName_2)
   ...
);

Notic: You cannot add a constraint to an existing table in sqlite. You can only rename table or add columns to a table.

CodePudding user response:

In addition to creating a unique index for the team name and handling the error that may have occurred when saving, you can check whether a team with this name already exists.

    private bool TeamExists(string name)
    {
      return _teamContext.Team.Any(e => e.Name == name);
    }
  • Related