0

I'm trying to add several objects to the DB with EF ObjectContext without calling the SaveChanges() after each add. Problem is that only the last added object is committed to the DB.

using (var entities = new ModelEntities())
{
    foreach (service in services)
    {
       entities.Services.AddObject(service);
    }
    entities.SaveChanges();
}

When I call the SaveChanges() method directly after AddObject all objects are inserted but performance is affected. What am I doing wrong?

Thanks.

0

1 Answer 1

1

Try:

using (var entities = new ModelEntities())
{
    foreach (var s in services)
    {
       var service = s;
       entities.Services.AddObject(service);
    }
    entities.SaveChanges();
}
Sign up to request clarification or add additional context in comments.

2 Comments

I don't see why this would produce any different performance results, it looks the same to me. can you explain what this will do and why it affects performance?
It's not about performance. The original code wasn't working because EF only added the last object referenced by service when the loop had finished. Here, service is scoped within the loop so every object is added. (Perhaps someone can do a better job of explaining!)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.