I am trying to work out a solution to check if any fields that should not be duplicated are having a row added that would break this rule. I am using the respository pattern so I wanted to create a method within the respository to do this.
In this example I am trying to add a company, in the controller before it's added it calls this method in the CompanyRespository:
public bool Exists(Company company, bool ignoreId)
{
if (!ignoreId)
{
if (context.Companies.Any(c => c.Id == company.Id)) return true;
}
if (context.Companies.Any(c => c.TextId == company.TextId)) return true;
if (context.Companies.Any(c => c.Email == company.Email)) return true;
if (context.Companies.Any(c => c.PhoneNumber == company.PhoneNumber)) return true;
return false;
}
The issue I am facing is trying to return the error so the controller can send the error to the client. The obvious solution would be to just send Exceptions instead of returning true. However, if I was to call this just to say if there is a company with these parameters then I dont want exceptions sent, I just want a boolean in both cases.
The cut down question: Is it bad practice to in this situation create another method CheckDuplication() which would return exceptions instead of a boolean? If yes then what is the correct way for checking duplicated fields before saving to the database in Entity Framework Core?