Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reverted bulk implementation #5047

Merged
merged 1 commit into from
Mar 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Linq.Expressions;
using EFCore.BulkExtensions;
using Elsa.Common.Models;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
Expand All @@ -18,10 +17,24 @@ public static class QueryableExtensions
/// </summary>
public static async Task BulkUpsertAsync<TDbContext, TEntity>(this TDbContext dbContext, IList<TEntity> entities, Expression<Func<TEntity, string>> keySelector, CancellationToken cancellationToken = default) where TDbContext : DbContext where TEntity : class
{
await dbContext.BulkInsertOrUpdateAsync(entities, new BulkConfig
{
EnableShadowProperties = true
}, cancellationToken: cancellationToken);
var set = dbContext.Set<TEntity>();
var compiledKeySelector = keySelector.Compile();
var containsLambda = entities.Any() ? keySelector.BuildContainsExpression(entities) : default;
var existingEntitiesQuery = set.AsNoTracking();

if (containsLambda != null)
existingEntitiesQuery = existingEntitiesQuery.Where(containsLambda);

var existingEntities = await existingEntitiesQuery.ToListAsync(cancellationToken);
var entitiesToUpdate = entities.IntersectBy(existingEntities.Select(compiledKeySelector), compiledKeySelector).ToList();
var entitiesToInsert = entities.Except(entitiesToUpdate).ToList();

if (entitiesToUpdate.Any())
set.UpdateRange(entitiesToUpdate);
if (entitiesToInsert.Any())
await set.AddRangeAsync(entitiesToInsert, cancellationToken);

await dbContext.SaveChangesAsync(cancellationToken);
}

/// <summary>
Expand Down
Loading