Entity Framework 6 Where in Bulk Update/Delete in one transaction

后端 未结 2 952
旧时难觅i
旧时难觅i 2021-01-18 12:35

In EF6, I want to update/delete bulk data in one query. My code is

 using (var context = _dataContextFactory.GetContext())
            {
                var         


        
2条回答
  •  长发绾君心
    2021-01-18 12:53

    Unfortunately, this is not supported in Entity Framework out of the box. However, you can use the batch update functionality in the EntityFramework.Extended library:

    https://github.com/loresoft/EntityFramework.Extended

    There's a nuget package available, too.

    An example would be:

    using EntityFramework.Extensions;
    
    ...
    
    int[] myIds = { 592, 593, 594 };
    
    using (var context = _dataContextFactory.GetContext())
    {
        // Define a filter expression to retrieve matching items
        var filter = context.MyTables.Where(item => myIds.Contains(item.Id));
        // Update the StatusId of matched items
        context.MyTables.Update(filter, i => new Item { StatusId = 3 });
    
        // NB: no context.SaveChanges() required
    }
    

    NB: there may be a more efficient way of writing this, but I'm still playing with the library. It does compile down to a single SQL statement, however, and the library also includes batched DELETEs.

    Finally, don't worry about the new expression. Any properties which are not referenced here will retain their original values.

提交回复
热议问题