SQL Server How to perform SQL batch updates in Entity Framework C#

jexiocij  于 2023-08-02  发布在  C#
关注(0)|答案(1)|浏览(127)

I have the following to perform a batch update in Azure table storage using Azure.Data.Tables:

public async Task BatchUpdateUsersAsync(IEnumerable<User> users)
{            
    var batchOperation = new List<TableTransactionAction>();

    if (users.Count() <= 100)
    {
        foreach (var user in users)
        {

            batchOperation.Add(new TableTransactionAction(TableTransactionActionType.UpdateMerge, user));
        }

        if (batchOperation.Any())
        {
            await _tableClient.SubmitTransactionAsync(batchOperation);
        }
    }
}

How do I perform a similar batch update in Azure SQL table using Entity Framework?

public class DatabaseRepo
{
    private readonly UserContext _context;
    
    public DatabaseRepo(UserContext userContext)
    {
        _context = userContext;
    }        

    public async Task BatchUpdateUsersAsync(IEnumerable<User> users)
    {            
        
    }
}
6mzjoqzu

6mzjoqzu1#

Ef Core does batching automatically.
The number of statements that EF batches in a single roundtrip depends on the database provider being used. For example, performance analysis has shown batching to be generally less efficient for SQL Server when less than 4 statements are involved. Similarly, the benefits of batching degrade after around 40 statements for SQL Server, so EF Core will by default only execute up to 42 statements in a single batch, and execute additional statements in separate roundtrips.

Just attach all the entities as Modified and run SaveChanges(). EG

public async Task BatchUpdateUsersAsync(IEnumerable<User> users)
{

    foreach (var user in users)
    {
        var entry = dbContext.Set<User>().Add(user);
        entry.State = EntityState.Modified;
    }

    await dbContext.SaveChangesAsync();
}

You can do this generically on your DbContext like this:

public async Task BatchUpdate<T>(IEnumerable<T> entities) where T: class
{

    foreach (var user in entities)
    {
        var entry = this.Set<T>().Add(user);
        entry.State = EntityState.Modified;
    }

    await this.SaveChangesAsync();
}

相关问题