A little assistance on how I can check if client already exists in the database before adding him or her into the database using a for loop in ASP.NET Core Web API.
I have a list of clients and I'm are trying to insert them into the database, but before I do that, I want to check if that client already exists. I am stuck here on how to do it - please help
This is my code:
foreach (Client client in clientList)
{
await _dbconnection.clients.AddAsync(client);
}
await _dbconnection.SaveChangesAsync();
CodePudding user response:
try this code
foreach (Client client in clientList)
{
var exist= await _dbconnection.clients.Any(x=> x.Id==client.Id)
if (!exist) _dbconnection.clients.Add(client);
}
await _dbconnection.SaveChangesAsync();