Update entities all at once

first100 81 Reputation points
2021-02-17T16:17:53.6+00:00

I have a list of entities returned me from external service,
in this list i would take only item with flag IsNew setted to true and save in my database.
My code is:

var entitiesLst
=ExternalService("BoxIt");

        foreach (var item in entitiesLst )
        {
            if (item.IsNew == true) 
                context.BoxIt.Update(item);
        }
        context.SaveChanges();

But i would like to do avoiding use of foreach cycle, there is any way to do this?

Thanks

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,219 questions
{count} votes

Accepted answer
  1. Alberto Poblacion 1,556 Reputation points
    2021-02-17T17:13:52.107+00:00

    Well, you can simulate that you are not using a loop by using LINQ:

    entitiesLst.Where(item => item.IsNew).ForEach(item => context.BoxIt.Update(item));

    But note that, internally, LINQ will use a loop to implement this.

    You can also use UpdateRange:

    context.BoxIt.UpdateRange(entitiesLst.Where(item => item.IsNew));

    But, again, the internal implementation for this method will actually use a loop.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,031 Reputation points
    2021-02-17T17:11:23.363+00:00

    You should be able to use AddRange of the DbContext e.g.

    public static void ForumQuestion(List<CustomerItem> list)
    {
        var resultList = list.Where(customer => customer.ContactTypeIdentifier == 9).ToList();
        using var context = new NorthwindContext();
        context.AddRange(resultList);
        context.SaveChanges();
    
    }
    

    Since I don't have your model these code samples use a model I have.

    Note If not using C#9

    public static void ForumQuestion(List<CustomerItem> list)
    {
        var resultList = list.Where(customer => customer.ContactTypeIdentifier == 9).ToList();
        using (var context = new NorthwindContext())
        {
            context.AddRange(resultList);
            context.SaveChanges();
        }
    }
    
    0 comments No comments