using AsbCloudApp.Data; using AsbCloudApp.Services; using AsbCloudApp.Comparators; using AsbCloudDb.Model; using AsbCloudInfrastructure.Services.Cache; using System.Collections.Generic; using System.Linq; namespace AsbCloudInfrastructure.Services { public class TelemetryUserService : ITelemetryUserService { private readonly IAsbCloudDbContext db; private readonly ITelemetryService telemetryService; private readonly CacheTable cacheTUsers; public TelemetryUserService(IAsbCloudDbContext db, CacheDb cacheDb, ITelemetryService telemetryService) { this.db = db; this.telemetryService = telemetryService; cacheTUsers = cacheDb.GetCachedTable((AsbCloudDbContext)db); } public void Upsert(string uid, IEnumerable dtos) { if (!dtos.Any()) return; dtos = dtos.Distinct(new TelemetryUserDtoComparer()); var telemetryId = telemetryService.GetOrCreateTemetryIdByUid(uid); var ids = dtos.Select(e => e.Id).ToList(); var dbIds = (from e in db.TelemetryUsers where e.IdTelemetry == telemetryId && ids.Contains(e.IdUser) select e.IdUser).ToList(); foreach (var dto in dtos) { var entity = new TelemetryUser { IdUser = dto.Id, IdTelemetry = telemetryId, Level = dto.Level, Name = dto.Name, Patronymic = dto.Patronymic, Surname = dto.Surname, }; if (dbIds.Contains(dto.Id)) db.TelemetryUsers.Update(entity); else db.TelemetryUsers.Add(entity); } db.SaveChanges(); cacheTUsers.Refresh(); } } }