using Application.Domain.Entities; using Infrastructure.Application; using Infrastructure.Data; using Infrastructure.Domain; using Infrastructure.Extensions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace IoT.Shared.Services { public class DataService { private readonly IConfiguration _cfg; private readonly IServiceProvider _services; private readonly IRepository _productRepo; private readonly IRepository _sceneRepo; private readonly IRepository _sceneCommandRepo; private readonly IRepository _iotTimerRepo; private readonly IRepository _iotTiggerRepo; public DataService(IConfiguration cfg, IServiceProvider services, IRepository nodeRepo, IRepository deviceRepo, IRepository dataRepo, IRepository apiRepo, IRepository commandRepo, IRepository categoryRepo, IRepository productRepo, IRepository sceneRepo, IRepository sceneCommandRepo, IRepository iotTimerRepo, IRepository iotTiggerRepo) { this._cfg = cfg; this._services = services; this._productRepo = productRepo; this._sceneRepo = sceneRepo; this._sceneCommandRepo = sceneCommandRepo; this._iotTimerRepo = iotTimerRepo; this._iotTiggerRepo = iotTiggerRepo; } public void UpdateList(string message, Expression> predicate) where T : BaseEntity { using var scope = this._services.CreateScope(); var repo = scope.ServiceProvider.GetService>(); var list = message.FromJson>(); var entities = repo.Table().Where(predicate).Where(o => !list.Contains(o.Id)).ToList(); foreach (var entity in entities) { repo.Delete(entity); } repo.SaveChanges(); } #region private public void Update(string message) where T : BaseEntity { using var scope = this._services.CreateScope(); var repo = scope.ServiceProvider.GetService>(); var model = message.FromJson(); var entity = repo.Table().FirstOrDefault(o => o.Id == model.Id); if (entity == null) { entity = Activator.CreateInstance(); repo.Add(entity); } entity.From(model); repo.SaveChanges(); } public void Edit(TEditModel model) where T : BaseEntity where TEditModel : EditModel { using var scope = this._services.CreateScope(); var repo = scope.ServiceProvider.GetService>(); var entity = repo.Table().FirstOrDefault(o => o.Id == model.Id); if (entity == null) { entity = Activator.CreateInstance(); repo.Add(entity); } entity.From(model); repo.SaveChanges(); } public void Delete(TEditModel model) where T : BaseEntity where TEditModel : EditModel { using var scope = this._services.CreateScope(); var repo = scope.ServiceProvider.GetService>(); var entity = repo.Table().FirstOrDefault(o => o.Id == model.Id); if (entity != null) { repo.Delete(entity); repo.SaveChanges(); } } #endregion private } }