84 lines
2.8 KiB
C#
84 lines
2.8 KiB
C#
using BlazorApp.Data;
|
|
using BlazorApp.Data.Context;
|
|
using BlazorApp.Interfaces.Repositories;
|
|
using BlazorApp.Shared.Queries;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using System.ComponentModel.DataAnnotations;
|
|
|
|
namespace BlazorApp.Repositories.Database
|
|
{
|
|
public class CustomerDatabaseRepository : ICustomerRepository
|
|
{
|
|
private readonly ApplicationDbContext _dbContext;
|
|
public CustomerDatabaseRepository(ApplicationDbContext dbContext)
|
|
{
|
|
this._dbContext = dbContext;
|
|
}
|
|
|
|
public async Task Delete(string id)
|
|
{
|
|
Customer data = await this.Get(id);
|
|
this._dbContext.Customers.Remove(data);
|
|
await this._dbContext.SaveChangesAsync();
|
|
}
|
|
|
|
public async Task<Customer> Get(string id)
|
|
{
|
|
Customer data = await this._dbContext.Customers.FindAsync(id);
|
|
if (data is null)
|
|
{
|
|
throw new KeyNotFoundException($"Customer with id: {id} not found");
|
|
}
|
|
return data;
|
|
}
|
|
|
|
public async Task<IEnumerable<Customer>> Query(CustomerQuery query)
|
|
{
|
|
return await this._dbContext.Customers
|
|
.OrderBy(x => x.Id)
|
|
.Skip(query.PageIndex * query.ResultsPerPage)
|
|
.Take(query.ResultsPerPage)
|
|
.ToListAsync();
|
|
}
|
|
|
|
public async Task Save(Shared.Models.Customer model)
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(model.Id))
|
|
{
|
|
throw new ValidationException($"Customer has already id: {model.Id}.");
|
|
}
|
|
Customer data = new Customer()
|
|
{
|
|
Id = Guid.NewGuid().ToString()
|
|
};
|
|
data.CompanyName = model.CompanyName;
|
|
data.ContactName = model.ContactName;
|
|
data.Address = model.Address;
|
|
data.City = model.City;
|
|
data.Region = model.Region;
|
|
data.PostalCode = model.PostalCode;
|
|
data.Country = model.Country;
|
|
data.Phone = model.Phone;
|
|
await this._dbContext.AddAsync(data);
|
|
await this._dbContext.SaveChangesAsync();
|
|
}
|
|
|
|
public async Task Update(Shared.Models.Customer model)
|
|
{
|
|
Customer data = await this.Get(model.Id);
|
|
data.CompanyName = model.CompanyName;
|
|
data.ContactName = model.ContactName;
|
|
data.Address = model.Address;
|
|
data.City = model.City;
|
|
data.Region = model.Region;
|
|
data.PostalCode = model.PostalCode;
|
|
data.Country = model.Country;
|
|
data.Phone = model.Phone;
|
|
this._dbContext.Update(data);
|
|
await this._dbContext.SaveChangesAsync();
|
|
}
|
|
|
|
public async Task<int> Count() => await this._dbContext.Customers.CountAsync();
|
|
}
|
|
}
|