...
Bloco de código |
---|
language | c# |
---|
firstline | 1 |
---|
title | EntityFrameworkCoreModule.cs |
---|
linenumbers | true |
---|
|
using Tnf.Reflection.Extensions;
using Tnf.App.EntityFrameworkCore;
using Tnf.Architecture.Domain;
using Tnf.Modules;
[DependsOn(
typeof(DomainModule),
typeof(TnfAppEntityFrameworkCoreModule))]
public class EntityFrameworkModule : TnfModule
{
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(EntityFrameworkModule).GetAssembly(Assembly));
}
} |
Podemos perceber em nosso módulo definido acima no atributo "DependsOn" fazendo referencia ao TnfAppEntityFrameworkCoreModule. Essa dependência comporta toda a estrutura necessária para a utilização do Entity Framework Core.
...
Bloco de código |
---|
language | c# |
---|
firstline | 1 |
---|
title | Country.cs |
---|
linenumbers | true |
---|
|
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Tnf.Architecture.Dto;
using Tnf.AutoMapper;
using Tnf.Domain.Entities;
[AutoMap(typeof(CountryDto))]
[Table("Countries")]
public class Country : Entity
{
public const int MaxNameLength = 256;
[Required]
[MaxLength(MaxNameLength)]
public string Name { get; set; }
public Country()
{
}
public Country(int id, string name)
{
Id = id;
Name = name;
}
} |
...
Bloco de código |
---|
language | c# |
---|
firstline | 1 |
---|
title | ICountryRepository.cs |
---|
linenumbers | true |
---|
|
public interface ICountryRepository : IRepository<Country>
{
} |
Essa interface está dentro do projeto de Domain para que ele não precise conhecer o projeto de Arquitetura.
Como instalamos o pacote Tnf.App.EntityFrameworkCore e configuramos a dependência do módulo TnfAppEntityFrameworkCoreModule, ao utilizar o tipo ICountryRepository para a entidade "Country", nosso mecanismo de injeção de dependência está injetando o repositório padrão EfCoreRepositoryBasepadrão AppEfCoreRepositoryBase com suporte a métodos para realizar operações de CRUD e queries mais complexas.
...
Bloco de código |
---|
language | c# |
---|
firstline | 1 |
---|
title | CustomCountryRepository.cs |
---|
linenumbers | true |
---|
|
public class CustomCountryRepository : EfCoreRepositoryBase<ArchitectureDbContextAppEfCoreRepositoryBase<ArchitectureDbContext, Country, int>, ICountryRepository
{
public ProfessionalRepository(IDbContextProvider<ArchitectureDbContext> dbContextProvider)
: base(dbContextProvider)
{
}
public override Professional Get(decimal id)
{
return base.Get(id);
}
} |
...
Bloco de código |
---|
language | c# |
---|
firstline | 1 |
---|
title | ProfessionalPoco.cs |
---|
linenumbers | true |
---|
|
using System;
using System.Collections.Generic;
using Tnf.Architecture.Dto.Registration;
using Tnf.AutoMapper;
using Tnf.Domain.Entities;
namespace Tnf.Architecture.EntityFrameworkCore.Entities
{
[AutoMap(typeof(ProfessionalDto))]
public class ProfessionalPoco : Entity
{
public ProfessionalPoco()
{
}
public decimal ProfessionalId { get; set; }
public string Name { get; set; }
public Guid Code { get; set; }
public string Address { get; set; }
public string AddressNumber { get; set; }
public string AddressComplement { get; set; }
public string ZipCode { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public List<ProfessionalSpecialtiesPoco> ProfessionalSpecialties { get; set; }
}
} |
...
Bloco de código |
---|
language | c# |
---|
firstline | 1 |
---|
title | IProfessionalRepository.cs |
---|
linenumbers | true |
---|
|
using System;
using System.Collections.Generic;
using Tnf.ArchitectureApp.DomainDto.RegistrationRequest;
using Tnf.Architecture.DtoCommon.RegistrationValueObjects;
using Tnf.Architecture.Domain.RepositoriesRegistration;
using Tnf.App.Dto.Request;
using Tnf.App.Dto.ResponseDomain.Repositories;
namespace Tnf.Architecture.Domain.Interfaces.Repositories
{
public interface IProfessionalRepository : IRepository
{
ListDto<ProfessionalDto>Professional GetAllProfessionalsGetProfessional(GetAllProfessionalsDto request);
ProfessionalDto GetProfessional(RequestDto<ProfessionalKeysDto> IRequestDto<ComposeKey<Guid, decimal>> requestDto);
ComposeKey<Guid, ProfessionalKeysDtodecimal> CreateProfessional(Professional entity);
Professionalvoid UpdateProfessional(Professional dtoentity);
bool DeleteProfessional(ProfessionalKeysDtoComposeKey<Guid, decimal> keys);
void AddOrRemoveSpecialties(ProfessionalKeysDtoComposeKey<Guid, decimal> keys, List<SpecialtyDto>IList<Specialty> dtospecialties);
bool ExistsProfessional(ProfessionalKeysDtoComposeKey<Guid, decimal> keys);
}
}
|
Bloco de código |
---|
language | c# |
---|
firstline | 1 |
---|
title | ProfessionalRepository.cs |
---|
linenumbers | true |
---|
|
using Microsoft.EntityFrameworkCore; using System;
using System.Collections.Generic;
using System.Linq;
; using System.Transactions; using Tnf.App.AutoMapper; using Tnf.App.Dto.Request;
; using Tnf.App.EntityFrameworkCore; using Tnf.App.Dto.Response;
.EntityFrameworkCore.Repositories; using Tnf.Architecture.Common.ValueObjects; using Tnf.Architecture.Domain.Interfaces.Repositories;
using Tnf.Architecture.Domain.Registration;
using Tnf.Architecture.Dto.Registration;
using Tnf.Architecture.EntityFrameworkCore.EntitiesContexts;
using Tnf.AutoMapper;
Architecture.EntityFrameworkCore.Entities; using Tnf.Domain.RepositoriesUow;
using Tnf.EntityFrameworkCore;
using Tnf.EntityFrameworkCore.Repositories;
namespace Tnf.Architecture.EntityFrameworkCore.Repositories
{
public class ProfessionalRepository : EfCoreRepositoryBase<LegacyDbContextAppEfCoreRepositoryBase<LegacyDbContext, ProfessionalPoco>, IProfessionalRepository
{
private readonly IUnitOfWorkManager _unitOfWorkManager; public ProfessionalRepository(IDbContextProvider<LegacyDbContext> dbContextProvider)
, IUnitOfWorkManager unitOfWorkManager) : base(dbContextProvider)
{ _unitOfWorkManager = unitOfWorkManager; } public {
}
public bool DeleteProfessional(ProfessionalKeysDto keys)
{
var dbEntity = Context.Professionals
.Include(i => i.ProfessionalSpecialties)
.SingleOrDefault(s => s.ProfessionalId == keys.ProfessionalId && s.Code == keys.Code);
if (dbEntity != null)
{
dbEntity.ProfessionalSpecialties.ForEach(w => Context.ProfessionalSpecialties.Remove(w));
Context.Professionals.Remove(dbEntity);
}
return dbEntity != null;
}
private ProfessionalPoco GetProfessionalPoco(RequestDto<ProfessionalKeysDto> requestDto)
{
var dbEntity = Context.Professionals
.IncludeByRequestDto(requestDto)
.Where(w => w.ProfessionalId == requestDto.GetId().ProfessionalId && w.Code == requestDto.GetId().Code)
.SelectFieldsByRequestDto(requestDto)
.SingleOrDefault();
return dbEntity;
}
public ProfessionalDto GetProfessional(RequestDto<ProfessionalKeysDto> requestDto)
{
var dbEntity = GetProfessionalPoco(requestDto);
var dto = dbEntity != null ? dbEntity.MapTo<ProfessionalDto>() : null;
dto.RemoveExpandable(requestDto);
return dto;
}
public ProfessionalKeysDto CreateProfessional(Professional entity)
{
var dbEntity = entity.MapTo<ProfessionalPoco>();
Context.Professionals.Add(dbEntity);
Context.SaveChanges();
return new ProfessionalKeysDto(dbEntity.ProfessionalId, dbEntity.Code);
}
public Professional UpdateProfessional(Professional entity)
{
var mappedEntity = GetProfessionalPoco(new RequestDto<ProfessionalKeysDto>(new ProfessionalKeysDto(entity.ProfessionalId, entity.Code)));
entity.MapTo(mappedEntity);
Context.Professionals.Update(mappedEntity);
Context.SaveChanges();
return entity;
}
public ListDto<ProfessionalDto> GetAllProfessionals(GetAllProfessionalsDto request)
{
var response = new ListDto<ProfessionalDto>();
var dbBaseQuery = Context.Professionals
.Include(i => i.ProfessionalSpecialties)
.ThenInclude(i => i.Specialty)
.Where(w => request.Name == null || w.Name.Contains(request.Name));
var dbQuery = dbBaseQuery
.SkipAndTakeByRequestDto(request)
.OrderByRequestDto(request)
.ToArray();
response.Total = base.Count();
response.Items = dbQuery.MapTo<List<ProfessionalDto>>();
response.HasNext = response.Total > ((request.Page - 1) * request.PageSize) + response.Items.Count();
return response;
}
public void AddOrRemoveSpecialties(ProfessionalKeysDto keys, List<SpecialtyDto> dto)
{
var request = new RequestDto<ProfessionalKeysDto>(keys);
request.Expand = new ProfessionalDto()._expandables[0];
var dbProfessional = GetProfessionalPoco(request);
if (dbProfessional != null)
{
var idsToAdd = dto.Select(s => s.Id).ToArray();
if (dbProfessional.ProfessionalSpecialties == null)
dbProfessional.ProfessionalSpecialties = new List<ProfessionalSpecialtiesPoco>();
dbProfessional.ProfessionalSpecialties.RemoveAll(w => !idsToAdd.Contains(w.SpecialtyId));
dto.ForEach(w =>
{
var dbProfessionalSpecialties = dbProfessional.ProfessionalSpecialties
.FirstOrDefault(s => s.SpecialtyId == w.Id);
if (dbProfessionalSpecialties == null)
{
dbProfessional.ProfessionalSpecialties.Add(new ProfessionalSpecialtiesPoco()
{
ProfessionalId = dbProfessional.ProfessionalId,
Code = dbProfessional.Code,
SpecialtyId = w.Id
});
}
});
}
}
public bool ExistsProfessional(ProfessionalKeysDto keys)
{
var dbEntity = Context.Professionals
.SingleOrDefault(s => s.ProfessionalId == keys.ProfessionalId && s.Code == keys.Code);
return dbEntity != null;
}
}
}
bool DeleteProfessional(ComposeKey<Guid, decimal> keys) { var dbEntity = Context.Professionals .Include(i => i.ProfessionalSpecialties) .SingleOrDefault(s => s.ProfessionalId == keys.SecundaryKey && s.Code == keys.PrimaryKey); if (dbEntity == null) return false; dbEntity.ProfessionalSpecialties.ForEach(w => Context.ProfessionalSpecialties.Remove(w)); Context.Professionals.Remove(dbEntity); return true; } private ProfessionalPoco GetProfessionalPoco(IRequestDto<ComposeKey<Guid, decimal>> requestDto) { var dbEntity = Context.Professionals .IncludeByRequestDto(requestDto) .Where(w => w.ProfessionalId == requestDto.GetId().SecundaryKey && w.Code == requestDto.GetId().PrimaryKey) .SelectFieldsByRequestDto(requestDto) .SingleOrDefault(); return dbEntity; } public Professional GetProfessional(IRequestDto<ComposeKey<Guid, decimal>> requestDto) { var dbEntity = GetProfessionalPoco(requestDto); if (dbEntity == null) return null; var dto = dbEntity.MapTo<Professional>(); return dto; } public ComposeKey<Guid, decimal> CreateProfessional(Professional entity) { var dbEntity = entity.MapTo<ProfessionalPoco>(); dbEntity.ProfessionalId = GetNextKeyProfessional(); Context.Professionals.Add(dbEntity); Context.SaveChanges(); return new ComposeKey<Guid, decimal>(dbEntity.Code, dbEntity.ProfessionalId); } private decimal GetNextKeyProfessional() { using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew)) { var lastKey = Context.Professionals.Select(s => s.ProfessionalId).DefaultIfEmpty(0).Max(); return (lastKey + 1); } } public void UpdateProfessional(Professional entity) { var mappedEntity = GetProfessionalPoco(new RequestDto<ComposeKey<Guid, decimal>>(new ComposeKey<Guid, decimal>(entity.Code, entity.ProfessionalId))); entity.MapTo(mappedEntity); Context.Professionals.Update(mappedEntity); Context.SaveChanges(); } public void AddOrRemoveSpecialties(ComposeKey<Guid, decimal> keys, IList<Specialty> specialties) { var request = new RequestDto<ComposeKey<Guid, decimal>>(keys) { Expand = new ProfessionalDto().Expandables[0] }; var dbProfessional = GetProfessionalPoco(request); if (dbProfessional == null) return; var idsToAdd = specialties.Select(s => s.Id).ToArray(); if (dbProfessional.ProfessionalSpecialties == null) dbProfessional.ProfessionalSpecialties = new List<ProfessionalSpecialtiesPoco>(); dbProfessional.ProfessionalSpecialties.RemoveAll(w => !idsToAdd.Contains(w.SpecialtyId)); foreach (var specialty in specialties) { var dbProfessionalSpecialties = dbProfessional.ProfessionalSpecialties .FirstOrDefault(s => s.SpecialtyId == specialty.Id); if (dbProfessionalSpecialties == null) { dbProfessional.ProfessionalSpecialties.Add(new ProfessionalSpecialtiesPoco { ProfessionalId = dbProfessional.ProfessionalId, Code = dbProfessional.Code, SpecialtyId = specialty.Id }); } } } public bool ExistsProfessional(ComposeKey<Guid, decimal> keys) { var dbEntity = Context.Professionals .SingleOrDefault(s => s.ProfessionalId == keys.SecundaryKey && s.Code == keys.PrimaryKey); return dbEntity != null; } } } |
Este exemplo com umas estrutura legada esta disponível em nosso github: https://github.com/totvsnetcore/tnf-samples/tree/master/TnfSample-Architecture
using Microsoft.EntityFrameworkCore;using System;using System.Collections.Generic;using System.Linq;using System.Transactions;using Tnf.App.AutoMapper;using Tnf.App.Dto.Request;using Tnf.App.EntityFrameworkCore;using Tnf.App.EntityFrameworkCore.Repositories;using Tnf.Architecture.Common.ValueObjects;using Tnf.Architecture.Domain.Interfaces.Repositories;using Tnf.Architecture.Domain.Registration;using Tnf.Architecture.Dto.Registration;using Tnf.Architecture.EntityFrameworkCore.Contexts;using Tnf.Architecture.EntityFrameworkCore.Entities;using Tnf.Domain.Uow;using Tnf.EntityFrameworkCore;
namespace Tnf.Architecture.EntityFrameworkCore.Repositories{ public class ProfessionalRepository : AppEfCoreRepositoryBase<LegacyDbContext, ProfessionalPoco>, IProfessionalRepository { private readonly IUnitOfWorkManager _unitOfWorkManager;
public ProfessionalRepository(IDbContextProvider<LegacyDbContext> dbContextProvider, IUnitOfWorkManager unitOfWorkManager) : base(dbContextProvider) { _unitOfWorkManager = unitOfWorkManager; }
public bool DeleteProfessional(ComposeKey<Guid, decimal> keys) { var dbEntity = Context.Professionals .Include(i => i.ProfessionalSpecialties) .SingleOrDefault(s => s.ProfessionalId == keys.SecundaryKey && s.Code == keys.PrimaryKey);
if (dbEntity == null) return false;
dbEntity.ProfessionalSpecialties.ForEach(w => Context.ProfessionalSpecialties.Remove(w));
Context.Professionals.Remove(dbEntity);
return true; }
private ProfessionalPoco GetProfessionalPoco(IRequestDto<ComposeKey<Guid, decimal>> requestDto) { var dbEntity = Context.Professionals .IncludeByRequestDto(requestDto) .Where(w => w.ProfessionalId == requestDto.GetId().SecundaryKey && w.Code == requestDto.GetId().PrimaryKey) .SelectFieldsByRequestDto(requestDto) .SingleOrDefault();
return dbEntity; }
public Professional GetProfessional(IRequestDto<ComposeKey<Guid, decimal>> requestDto) { var dbEntity = GetProfessionalPoco(requestDto);
if (dbEntity == null) return null;
var dto = dbEntity.MapTo<Professional>();
return dto; }
public ComposeKey<Guid, decimal> CreateProfessional(Professional entity) { var dbEntity = entity.MapTo<ProfessionalPoco>();
dbEntity.ProfessionalId = GetNextKeyProfessional();
Context.Professionals.Add(dbEntity);
Context.SaveChanges();
return new ComposeKey<Guid, decimal>(dbEntity.Code, dbEntity.ProfessionalId); }
private decimal GetNextKeyProfessional() { using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew)) { var lastKey = Context.Professionals.Select(s => s.ProfessionalId).DefaultIfEmpty(0).Max(); return (lastKey + 1); } }
public void UpdateProfessional(Professional entity) { var mappedEntity = GetProfessionalPoco(new RequestDto<ComposeKey<Guid, decimal>>(new ComposeKey<Guid, decimal>(entity.Code, entity.ProfessionalId)));
entity.MapTo(mappedEntity);
Context.Professionals.Update(mappedEntity);
Context.SaveChanges(); }
public void AddOrRemoveSpecialties(ComposeKey<Guid, decimal> keys, IList<Specialty> specialties) { var request = new RequestDto<ComposeKey<Guid, decimal>>(keys) { Expand = new ProfessionalDto().Expandables[0] };
var dbProfessional = GetProfessionalPoco(request);
if (dbProfessional == null) return;
var idsToAdd = specialties.Select(s => s.Id).ToArray();
if (dbProfessional.ProfessionalSpecialties == null) dbProfessional.ProfessionalSpecialties = new List<ProfessionalSpecialtiesPoco>();
dbProfessional.ProfessionalSpecialties.RemoveAll(w => !idsToAdd.Contains(w.SpecialtyId));
foreach (var specialty in specialties) { var dbProfessionalSpecialties = dbProfessional.ProfessionalSpecialties .FirstOrDefault(s => s.SpecialtyId == specialty.Id);
if (dbProfessionalSpecialties == null) { dbProfessional.ProfessionalSpecialties.Add(new ProfessionalSpecialtiesPoco { ProfessionalId = dbProfessional.ProfessionalId, Code = dbProfessional.Code, SpecialtyId = specialty.Id }); } } }
public bool ExistsProfessional(ComposeKey<Guid, decimal> keys) { var dbEntity = Context.Professionals .SingleOrDefault(s => s.ProfessionalId == keys.SecundaryKey && s.Code == keys.PrimaryKey);
return dbEntity != null; } }}Este exemplo com umas estrutura legada esta disponível em nosso github: https://github.com/totvsnetcore/tnf-samples/tree/master/TnfSample-Architecture