user4189129
user4189129

Reputation:

Adding/updating a lot of rows in 1 call with Entity Framework

I have written some code which should check if a row already exists, if not it adds it and if it does it will add it. Afterwards it calls the SaveChanges() function. I'm just wondering if I have done this correctly.

Here is my code.

using (var ctx = _context)
    {
        foreach (var item in objects)
        {
            Object existingRow = ctx.Objects.Where(x => x.Id == item.Id).FirstOrDefault();
            if (existingRow != null)
                existingRow = item;
            else
                ctx.Objects.Add(item);
        }
        ctx.SaveChanges();
    }

Here is _context my context to the database.

Is this the correct way in doing this? Does executing SaveChanges() really result in only 1 call even though I add a lot of objects to the context?

Objects is a list which can be as big as 1000+ objects.

Thank you in advance for your help!

Upvotes: 0

Views: 45

Answers (1)

Emad
Emad

Reputation: 3939

Yes that's how you should do it. The exact way that EF does it is depending on internal algorithms but they are usually well formatted.

Also if you want to know how it does it or you want to change the way EF does something you should use Interception

Upvotes: 1

Related Questions