diff --git a/Models/CommonDbContext.cs b/Models/CommonDbContext.cs index 12a1e16..7f82e39 100644 --- a/Models/CommonDbContext.cs +++ b/Models/CommonDbContext.cs @@ -110,7 +110,7 @@ public abstract class CommonDbContext : DbContext } public async Task FindOrCreateAsync(Expression> predicate, Func factory) where T : class { - var entity = ChangeTracker.Entries().Select(x => x.Entity).FirstOrDefault(predicate.Compile()); + var entity = ChangeTracker.Entries().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().FirstOrDefaultAsync(predicate); @@ -153,13 +150,7 @@ public abstract class CommonDbContext : DbContext } public T FindOrCreate(Expression> predicate, Func factory) where T : class { - var entity = ChangeTracker.Entries().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().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().FirstOrDefault(predicate); } + //find in change tracker + if (entity != null && Entry(entity).State == EntityState.Deleted) + { + Entry(entity).State = EntityState.Detached; + + entity = Set().FirstOrDefault(predicate); + } + //find in up-to-date db if (entity == null) { var newAppDB = CreateCopy(); entity = newAppDB.Set().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(); } -} \ No newline at end of file +}