diff --git a/Models/CommonDbContext.cs b/Models/CommonDbContext.cs index 1b36e3c..5c9780a 100644 --- a/Models/CommonDbContext.cs +++ b/Models/CommonDbContext.cs @@ -21,6 +21,8 @@ namespace NejCommon.Models; { } + public abstract CommonDbContext CreateCopy(); + public async Task ApiSaveChangesAsync() { try @@ -78,19 +80,22 @@ namespace NejCommon.Models; { var entity = ChangeTracker.Entries().Select(x => x.Entity).FirstOrDefault(predicate.Compile()); + //find in change tracker if (entity != null && Entry(entity).State == EntityState.Deleted) { Entry(entity).State = EntityState.Modified; } + //find in currentDb if (entity == null) { entity = await Set().FirstOrDefaultAsync(predicate); } + //find in up-to-date db if (entity == null) { - var newAppDB = Activator.CreateInstance(this.GetType()) as CommonDbContext; + var newAppDB = CreateCopy(); entity = await newAppDB.Set().FirstOrDefaultAsync(predicate); @@ -98,6 +103,8 @@ namespace NejCommon.Models; if (entity != null && this.Entry(entity).State == EntityState.Detached) Attach(entity); } + + //create if not found if (entity == null) { var newEntity = factory(); @@ -110,15 +117,30 @@ namespace NejCommon.Models; 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()); - //var entity = this.; + + //find in change tracker + if (entity != null && Entry(entity).State == EntityState.Deleted) + { + Entry(entity).State = EntityState.Modified; + } + + //find in currentDb if (entity == null) { - var newAppDB = Activator.CreateInstance(this.GetType()) as CommonDbContext; + entity = Set().FirstOrDefault(predicate); + } + + //find in up-to-date db + if (entity == null) + { + var newAppDB = CreateCopy(); entity = newAppDB.Set().FirstOrDefault(predicate); if (entity != null) Attach(entity); } + + //create if not found if (entity == null) { var newEntity = factory();