L
L
lucky42021-05-07 20:28:12
C++ / C#
lucky4, 2021-05-07 20:28:12

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


I know that the problem is in the IsDublicated function, which returns false all the time. But, I don’t understand how I can throw the appropriate status after execution ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2021-05-07
@lucky4

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

And in the AddAsync function you have the wrong condition. Should be:
if (await _unitOfWork.ProductRepository.IsDublicated(product.Label))
{
     throw new DataDublication("Label already exists.");
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question