using ClientsContracts.StorageContracts; using ClientsContracts.BindingModels; using ClientsContracts.ViewModels; using ClientsDatabaseImplement.Models; namespace ClientsDatabaseImplement.Implements { public class StatusStorage : IStatusStorage { public void Delete(StatusBindingModel model) { var context = new ClientsDatabase(); var status = context.Statuses.FirstOrDefault(rec => rec.Id == model.Id); if (status != null) { context.Statuses.Remove(status); context.SaveChanges(); } else { throw new Exception("Статус не найден"); } } public StatusViewModel GetElement(StatusBindingModel model) { if (model == null) { return null; } using var context = new ClientsDatabase(); var status = context.Statuses .ToList() .FirstOrDefault(rec => rec.Id == model.Id || rec.Name == model.Name); return status != null ? CreateModel(status) : null; } public List GetFilteredList(StatusBindingModel model) { if (model == null) { return null; } using var context = new ClientsDatabase(); return context.Statuses .Where(rec => rec.Name.Contains(model.Name)) .Select(CreateModel) .ToList(); } public List GetFullList() { using var context = new ClientsDatabase(); return context.Statuses .Select(CreateModel) .ToList(); } public void Insert(StatusBindingModel model) { var context = new ClientsDatabase(); var transaction = context.Database.BeginTransaction(); try { context.Statuses.Add(CreateModel(model, new Status())); context.SaveChanges(); transaction.Commit(); } catch { transaction.Rollback(); throw; } } public void Update(StatusBindingModel model) { var context = new ClientsDatabase(); var transaction = context.Database.BeginTransaction(); try { var status = context.Statuses.FirstOrDefault(rec => rec.Id == model.Id); if (status == null) { throw new Exception("Статус не найден"); } CreateModel(model, status); context.SaveChanges(); transaction.Commit(); } catch { transaction.Rollback(); throw; } } private static Status CreateModel(StatusBindingModel model, Status status) { status.Name = model.Name; return status; } private static StatusViewModel CreateModel(Status status) { return new StatusViewModel { Id = status.Id, Name = status.Name }; } } }