Fixup AddOrCreateAsync

This commit is contained in:
honzapatCZ 2026-10-27 15:04:29 +01:00
parent bebc2d9df7
commit ebd8f5be92

View File

@ -110,7 +110,7 @@ public abstract class CommonDbContext : DbContext
}
public async Task<T> FindOrCreateAsync<T>(Expression<Func<T, bool>> predicate, Func<T> factory) where T : class
{
var entity = ChangeTracker.Entries<T>().Select(x => x.Entity).FirstOrDefault(predicate.Compile());
var entity = ChangeTracker.Entries<T>().ToArray().Select(x => x.Entity).FirstOrDefault(predicate.Compile());
//find in currentDb
if (entity == null)
@ -121,9 +121,6 @@ public abstract class CommonDbContext : DbContext
//find in change tracker
if (entity != null && Entry(entity).State == EntityState.Deleted)
{
/*
Entry(entity).State = EntityState.Modified;
Attach(entity);*/
Entry(entity).State = EntityState.Detached;
entity = await Set<T>().FirstOrDefaultAsync(predicate);
@ -153,13 +150,7 @@ public abstract class CommonDbContext : DbContext
}
public T FindOrCreate<T>(Expression<Func<T, bool>> predicate, Func<T> factory) where T : class
{
var entity = ChangeTracker.Entries<T>().Where(e => e.State != EntityState.Deleted).Select(x => x.Entity).FirstOrDefault(predicate.Compile());
//find in change tracker
if (entity != null && Entry(entity).State == EntityState.Deleted)
{
Entry(entity).State = EntityState.Modified;
}
var entity = ChangeTracker.Entries<T>().ToArray().Select(x => x.Entity).FirstOrDefault(predicate.Compile());
//find in currentDb
if (entity == null)
@ -167,13 +158,23 @@ public abstract class CommonDbContext : DbContext
entity = Set<T>().FirstOrDefault(predicate);
}
//find in change tracker
if (entity != null && Entry(entity).State == EntityState.Deleted)
{
Entry(entity).State = EntityState.Detached;
entity = Set<T>().FirstOrDefault(predicate);
}
//find in up-to-date db
if (entity == null)
{
var newAppDB = CreateCopy();
entity = newAppDB.Set<T>().FirstOrDefault(predicate);
if (entity != null)
//track the entity if it's not null and not already being tracked
if (entity != null && this.Entry(entity).State == EntityState.Detached)
Attach(entity);
}
@ -276,4 +277,4 @@ public abstract class CommonDbContext : DbContext
{
this.ChangeTracker.DetectChanges();
}
}
}