using AsbCloudApp.Services; using AsbCloudDb.Model; using Microsoft.EntityFrameworkCore; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services { public class UserSettingsRepository : IUserSettingsRepository { private readonly IAsbCloudDbContext context; public UserSettingsRepository(IAsbCloudDbContext context) { this.context = context; } public Task GetOrDefaultAsync(int userId, string key, CancellationToken token) => context.Set() .Where(s => s.IdUser == userId && s.Key == key) .Select(s=>s.Value) .FirstOrDefaultAsync(token); public async Task InsertAsync(int userId, string key, object value, CancellationToken token) { var set = context.Set(); if (await set.AnyAsync(s=>s.IdUser == userId && s.Key == key, token)) return IUserSettingsRepository.ErrorKeyIsUsed; var entity = new UserSetting { IdUser = userId, Key = key, Value = value, }; context.Set() .Add(entity); return await context.SaveChangesAsync(token); } public async Task UpdateAsync(int userId, string key, object value, CancellationToken token) { var set = context.Set(); var updatingItem = await set .FirstOrDefaultAsync(s => s.IdUser == userId && s.Key == key, token); if (updatingItem is null) return IUserSettingsRepository.ErrorKeyNotFound; updatingItem.Value = value; set.Update(updatingItem); return await context.SaveChangesAsync(token); } public async Task DeleteAsync(int userId, string key, CancellationToken token) { var set = context.Set(); var removingItem = await set .FirstOrDefaultAsync(s=>s.IdUser == userId && s.Key ==key, token); if(removingItem is null) return IUserSettingsRepository.ErrorKeyNotFound; set.Remove(removingItem); return await context.SaveChangesAsync(token); } } }