Entity Framework bulk transactions written for .NET Core 3.1
Woodman.EntityFrameworkCore.Bulk provides a free set of extensions that provide a quick, simple way to perform bulk transactions against an EntityFramwork DbContext. Currently, it supports SqlServer, NgpSql, and InMemory Providers.
Install-Package Woodman.EntityFrameworkCore.Bulk
Avoid multiple DB round trips while still using Entity Framework patterns.
For a given bulk update:
using var db = new DbContext("connectionstring");
await db.Human
.Where(e => e.FirstName == null)
.BulkUpdateAsync(() => new Human
{
FirstName = "Joe"
});
Produces the following SQL statement:
UPDATE [h]
SET
[h].[FirstName] = @firstName
FROM [dbo].[Human] AS [h]
WHERE [h].[FirstName] IS NULL
By default, EF will generate a WHERE IN command when you pass a list of IDs into a WHERE clause.
Wraps the SQL generated by the IQueryable, and add a JOIN against the primary key.
using(var dbContext = new DbContext(c))
{
var ids = new int[] { 123, 1234, 12345 };
var queryable = dbContext.Entity.Join(ids);
var entities = await queryable.Entity.ToListAsync();
}
IQueryable.BulkRemoveAsnc(IEnumerable id)
Similar to the Join Operation above, wraps the EF and performs a single statement.
using(var dbContext = new DbContext(c))
{
var ids = new int[] { 123, 1234, 12345 };
int numDeleted = await dbContext.Entity.BulkRemoveAsync(ids);
}
using(var dbContext = new DbContext(c))
{
var entities = new List<Entity>();
entites.Add(new Entity { Name = "E1" };
entites.Add(new Entity { Name = "E2" };
// sets the PrimaryKey if generated by the DB
await dbContext.Entity.BulkAddAsync(entities);
}
using(var dbContext = new DbContext(c))
{
// update a set of records using a constructor expression
await dbContext.Entity.BulkUpdateAsync(() => new Entity
{
UpdatedDate = DateTime.UtcNow
});
// optionally pass in a set of ids to update records using the corresponding id
var ids = new int[] { 123, 1234, 12345 };
await dbContext.Entity.BulkUpdateAsync(ids, id => new Entity
{
UpdatedDate = id === 123 ? DateTime.UtcNow : DateTime.UtcNow.AddDays(1)
});
}
using(var dbContext = new DbContext(c))
{
var entities = new List<Entity>();
entites.Add(new Entity { Id = 1, Name = "E1" };
entites.Add(new Entity { Name = "E2" };
// sets the PrimaryKey if generated by the DB
var numRowsAffected = await dbContext.Entity.BulkMergeAsync(entities);
}