Answer the question
In order to leave comments, you need to log in
How to avoid duplicate names?
There is a product, each new product must have a different name. How to write a function that will check if the name of a new product is the same as any other product?
public async Task<ProductDto> AddAsync(ProductDto item)
{
Product product = _mapper.Map<Product>(item);
if (!await _unitOfWork.ProductRepository.IsDublicated(product.Label))
{
throw new DataDublication("Label already exists.");
}
await _unitOfWork.ProductRepository.AddAsync(product);
return _mapper.Map<ProductDto>(product);
}
public async Task<bool> IsDublicated(string label)
{
bool flag = false;
var check = await _context.Set<Product>()
.FirstOrDefaultAsync(property => property.Label.ToLower() == label.ToLower());
return flag;
}
Answer the question
In order to leave comments, you need to log in
IsDublicated always returns false because it's written incorrectly. You initialize a flag, then return it unchanged.
Try like this
public async Task<bool> IsDublicated(string label)
{
var existedProduct = await _context.Set<Product>()
.FirstOrDefaultAsync(property => property.Label.ToLower() == label.ToLower());
return existedProduct != null;
}
if (await _unitOfWork.ProductRepository.IsDublicated(product.Label))
{
throw new DataDublication("Label already exists.");
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question