...
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.Architecture.AutoMapperEntityFrameworkCore.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
{
publicprivate ProfessionalRepository(IDbContextProvider<LegacyDbContext> dbContextProvider)
readonly IUnitOfWorkManager _unitOfWorkManager;
public ProfessionalRepository(IDbContextProvider<LegacyDbContext> dbContextProvider, IUnitOfWorkManager unitOfWorkManager)
: base(dbContextProvider)
{
_unitOfWorkManager = unitOfWorkManager;
}
public bool DeleteProfessional(ProfessionalKeysDtoComposeKey<Guid, decimal> keys)
{
var dbEntity = Context.Professionals
.Include(i => i.ProfessionalSpecialties)
.SingleOrDefault(s => s.ProfessionalId == keys.ProfessionalIdSecundaryKey && s.Code == keys.CodePrimaryKey);
if (dbEntity !== null)
{
return false;
dbEntity.ProfessionalSpecialties.ForEach(w => Context.ProfessionalSpecialties.Remove(w));
Context.Professionals.Remove(dbEntity);
}
return true;
return dbEntity != null;
}}
private ProfessionalPoco GetProfessionalPoco(RequestDto<ProfessionalKeysDto>IRequestDto<ComposeKey<Guid, decimal>> requestDto)
{
var dbEntity = Context.Professionals
.IncludeByRequestDto(requestDto)
.Where(w => w.ProfessionalId == requestDto.GetId().ProfessionalIdSecundaryKey && w.Code == requestDto.GetId().CodePrimaryKey)
.SelectFieldsByRequestDto(requestDto)
.SingleOrDefault();
return dbEntity;
}
public ProfessionalDtoProfessional GetProfessional(RequestDto<ProfessionalKeysDto>IRequestDto<ComposeKey<Guid, decimal>> requestDto)
{
var dbEntity = GetProfessionalPoco(requestDto);
varif dto(dbEntity = dbEntity != null)
? dbEntity.MapTo<ProfessionalDto>() : null;
dto.RemoveExpandable(requestDto)return null;
returnvar dto;
= dbEntity.MapTo<Professional>();
return dto;
}
public ProfessionalKeysDtoComposeKey<Guid, decimal> CreateProfessional(Professional entity)
{
var dbEntity = entity.MapTo<ProfessionalPoco>();
dbEntity.ProfessionalId = GetNextKeyProfessional();
Context.Professionals.Add(dbEntity);
Context.SaveChanges();
return new ProfessionalKeysDtoComposeKey<Guid, decimal>(dbEntity.ProfessionalIdCode, dbEntity.CodeProfessionalId);
}
publicprivate Professionaldecimal UpdateProfessionalGetNextKeyProfessional(Professional entity)
{
using (var mappedEntityuow = GetProfessionalPoco(new RequestDto<ProfessionalKeysDto>(new ProfessionalKeysDto(entity.ProfessionalId, entity.Code)));
_unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
entity.MapTo(mappedEntity);
{
Context.Professionals.Update(mappedEntity);
var lastKey = Context.Professionals.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));
Select(s => s.ProfessionalId).DefaultIfEmpty(0).Max();
var dbQuery = dbBaseQuery
return (lastKey + 1);
.SkipAndTakeByRequestDto(request)}
}
public void .OrderByRequestDto(requestUpdateProfessional(Professional entity)
{
.ToArray();
var mappedEntity = GetProfessionalPoco(new RequestDto<ComposeKey<Guid, decimal>>(new response.Total = base.Count();ComposeKey<Guid, decimal>(entity.Code, entity.ProfessionalId)));
response.Items = dbQuery.MapTo<List<ProfessionalDto>>(entity.MapTo(mappedEntity);
response.HasNext = response.Total > ((request.Page - 1) * request.PageSize) + response.Items.Count()Context.Professionals.Update(mappedEntity);
return responseContext.SaveChanges();
}
public void AddOrRemoveSpecialties(ProfessionalKeysDto AddOrRemoveSpecialties(ComposeKey<Guid, decimal> keys, List<SpecialtyDto>IList<Specialty> dtospecialties)
{
var request = new RequestDto<ComposeKey<Guid, RequestDto<ProfessionalKeysDto>decimal>>(keys);
request. { Expand = new ProfessionalDto()._expandablesExpandables[0] };
var dbProfessional = GetProfessionalPoco(request);
if (dbProfessional !== null)
{
return;
var idsToAdd = dtospecialties.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 dto.ForEach(w =>in specialties)
{
{
var dbProfessionalSpecialties = dbProfessional.ProfessionalSpecialties
.FirstOrDefault(s => s.SpecialtyId == wspecialty.Id);
if (dbProfessionalSpecialties == null)
{
dbProfessional.ProfessionalSpecialties.Add(new ProfessionalSpecialtiesPoco()
{
ProfessionalId = dbProfessional.ProfessionalId,
Code = dbProfessional.Code,
SpecialtyId = wspecialty.Id
});
}
});
}
}
public bool ExistsProfessional(ProfessionalKeysDtoComposeKey<Guid, decimal> keys)
{
var dbEntity = Context.Professionals
.SingleOrDefault(s => s.ProfessionalId == keys.ProfessionalIdSecundaryKey && s.Code == keys.CodePrimaryKey);
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
...