Set up multi-project solution with DbFirst API, Application, Domain, and Infrastructure layers. Implemented database-first EF Core for the Catalog entity, including domain, DTOs, repository, service, and controller. Configured AutoMapper, DI, Swagger, and project settings. Added .gitattributes and initial configuration files.
67 lines
2.2 KiB
C#
67 lines
2.2 KiB
C#
using AutoMapper;
|
|
using DbFirst.Domain.DomainEntities;
|
|
using DbFirst.Domain.Repositories;
|
|
using DbFirst.Infrastructure.ScaffoldEntities;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace DbFirst.Infrastructure.Repositories;
|
|
|
|
public class CatalogRepository : ICatalogRepository
|
|
{
|
|
private readonly ApplicationDbContext _db;
|
|
private readonly IMapper _mapper;
|
|
|
|
public CatalogRepository(ApplicationDbContext db, IMapper mapper)
|
|
{
|
|
_db = db;
|
|
_mapper = mapper;
|
|
}
|
|
|
|
public async Task<List<Catalog>> GetAllAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
var entities = await _db.TbmyCatalogs.AsNoTracking().ToListAsync(cancellationToken);
|
|
return _mapper.Map<List<Catalog>>(entities);
|
|
}
|
|
|
|
public async Task<Catalog?> GetByIdAsync(int id, CancellationToken cancellationToken = default)
|
|
{
|
|
var entity = await _db.TbmyCatalogs.AsNoTracking().FirstOrDefaultAsync(x => x.Guid == id, cancellationToken);
|
|
return entity == null ? null : _mapper.Map<Catalog>(entity);
|
|
}
|
|
|
|
public async Task<Catalog> AddAsync(Catalog catalog, CancellationToken cancellationToken = default)
|
|
{
|
|
var entity = _mapper.Map<TbmyCatalog>(catalog);
|
|
_db.TbmyCatalogs.Add(entity);
|
|
await _db.SaveChangesAsync(cancellationToken);
|
|
return _mapper.Map<Catalog>(entity);
|
|
}
|
|
|
|
public async Task<bool> UpdateAsync(int id, Catalog catalog, CancellationToken cancellationToken = default)
|
|
{
|
|
var entity = await _db.TbmyCatalogs.FirstOrDefaultAsync(x => x.Guid == id, cancellationToken);
|
|
if (entity == null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
_mapper.Map(catalog, entity);
|
|
entity.Guid = id;
|
|
await _db.SaveChangesAsync(cancellationToken);
|
|
return true;
|
|
}
|
|
|
|
public async Task<bool> DeleteAsync(int id, CancellationToken cancellationToken = default)
|
|
{
|
|
var entity = await _db.TbmyCatalogs.FirstOrDefaultAsync(x => x.Guid == id, cancellationToken);
|
|
if (entity == null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
_db.TbmyCatalogs.Remove(entity);
|
|
await _db.SaveChangesAsync(cancellationToken);
|
|
return true;
|
|
}
|
|
}
|