using ClientsContracts.StorageContracts; using ClientsContracts.BindingModels; using ClientsContracts.ViewModels; using ClientsDatabaseImplement.Models; namespace ClientsDatabaseImplement.Implements { public class ClientStorage : IClientStorage { public void Delete(ClientBindingModel model) { var context = new ClientsDatabase(); var client = context.Clients.FirstOrDefault(rec => rec.Id == model.Id); if (client != null) { context.Clients.Remove(client); context.SaveChanges(); } else { throw new Exception("Клиент не найден"); } } public ClientViewModel GetElement(ClientBindingModel model) { if (model == null) { return null; } using var context = new ClientsDatabase(); var client = context.Clients .ToList() .FirstOrDefault(rec => rec.Id == model.Id); return client != null ? CreateModel(client) : null; } public List GetFilteredList(ClientBindingModel model) { var context = new ClientsDatabase(); return context.Clients .Where(client => client.Name.Contains(model.Name) && client.Status.Contains(model.Status)) .ToList() .Select(CreateModel) .ToList(); } public List GetFullList() { using (var context = new ClientsDatabase()) { return context.Clients .ToList() .Select(CreateModel) .ToList(); } } public void Insert(ClientBindingModel model) { var context = new ClientsDatabase(); var transaction = context.Database.BeginTransaction(); try { context.Clients.Add(CreateModel(model, new Client())); context.SaveChanges(); transaction.Commit(); } catch { transaction.Rollback(); throw; } } public void Update(ClientBindingModel model) { var context = new ClientsDatabase(); var transaction = context.Database.BeginTransaction(); try { var client = context.Clients.FirstOrDefault(rec => rec.Id == model.Id); if (client == null) { throw new Exception("Клиент не найден"); } CreateModel(model, client); context.SaveChanges(); transaction.Commit(); } catch { transaction.Rollback(); throw; } } private static Client CreateModel(ClientBindingModel model, Client client) { client.Amount = model.Amount; client.Name = model.Name; client.Status = model.Status; client.Reviews = model.Reviews; return client; } private ClientViewModel CreateModel(Client client) { return new ClientViewModel { Id = client.Id, Amount = client.Amount, Name = client.Name, Status = client.Status, Reviews = client.Reviews }; } } }