Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Check if multiple records exist before insert

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?

like image 868
blgrnboy Avatar asked Sep 16 '25 00:09

blgrnboy


1 Answers

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);
like image 178
Tyler Jennings Avatar answered Sep 18 '25 17:09

Tyler Jennings