0

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!

4
  • SaveChanges will result in one call, but "ctx.Objects.Where(x => x.Id == item.Id).FirstOrDefault()" will also result in query to database, and for 1000 objects that will be 1000 calls. Commented Nov 15, 2016 at 8:46
  • What would be the best way of checking if the object already exists without making those calls? Commented Nov 15, 2016 at 9:02
  • Well, the answer from @SlavaUtesinov was valid, but it's now deleted unfortunately. Instead of changing AutoDetectChangesEnabled, you can also use AddRange(yourItems) to add many items to the context at once (but even with AutoDetectChangesEnabled it was still perfectly valid answer). Commented Nov 15, 2016 at 9:18
  • But note that Contains is slow in EF for large sets (say for 10000 items it will be VERY slow). If you want to make it really fast, you will have to write the check for existance in raw sql. Commented Nov 15, 2016 at 9:22

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I'm still fairly new to EF so I'll definitely use interception!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.