I'm trying to figure out the best way to insert multiple records (over 200) if they do not exist, without making a trip for each record to check if it exists, which I do like this:
foreach (var node in nodes)
{
if (!context.Nodes.Any(x => x.Name == node.Name))
{
context.Nodes.Add(new NWatchNode(node));
}
try
{
if (context.Nodes.Local.Any())
{
context.SaveChanges();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
What is the best way to do this?
Assuming that node.Name
is unique in the table in the database, you could do something like this narrow your list of nodes to ones that don't exist:
var missingRecords = nodes.Where(x => !context.Nodes.Any(z => z.Name == x.Name)).ToList();
Then insert the missing records with something like:
context.Nodes.AddRange(missingRecords);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With