refact ef update

This commit is contained in:
eugeniy_ivanov 2023-02-06 21:33:53 +05:00
parent ff12c17496
commit 973f1afb1b
2 changed files with 18 additions and 7 deletions

View File

@ -1,8 +1,10 @@
using AsbCloudDb.Model.Subsystems;
using AsbCloudDb.Model.WITS;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
@ -70,6 +72,7 @@ namespace AsbCloudDb.Model
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
DbSet<TEntity> Set<TEntity>(string name) where TEntity : class;
DbSet<TEntity> Set<TEntity>() where TEntity : class;
EntityEntry<TEntity> Entry<TEntity>([NotNull] TEntity entity) where TEntity : class;
}
}

View File

@ -103,16 +103,24 @@ namespace AsbCloudInfrastructure.Repository
var userRoles = await userRoleRepository.GetByNamesAsync(dto.RoleNames, token).ConfigureAwait(false);
await UpdateRolesCacheForUserAsync(dto.Id, userRoles, token);
var userInDb = dbContext.Users.FirstOrDefault(u => u.Id == dto.Id);
if (userInDb is not null)
{
userInDb = Convert(dto);
await dbContext.SaveChangesAsync(token);
}
var entity = Convert(dto);
var local = dbContext.Set<User>()
.Local
.FirstOrDefault(entry => entry.Id.Equals(entity.Id));
if (local != null)
{
dbContext.Entry(local).State = EntityState.Detached;
}
dbContext.Entry(entity).State = EntityState.Modified;
await dbContext.SaveChangesAsync(token);
DropCacheUsers();
return userInDb!.Id;
return entity.Id;
}
public async Task<int> DeleteAsync(int id, CancellationToken token)
{
var dto = (await GetCacheUserAsync(token)).FirstOrDefault(u => u.Id == id);