Reputation: 43
Code :
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);
}
}
Team names should be unique. Using Entity Framework how to validate that?
Upvotes: 1
Views: 546
Reputation: 48357
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.
Upvotes: 2
Reputation: 447
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.
Upvotes: 1