BaseRepository implementado

Siguiente video: 50 Implementar metodos personalizados
This commit is contained in:
Alejandro Sarmiento
2024-02-17 13:35:47 +01:00
parent ed5a0cceb0
commit 7ada54dbf5
55 changed files with 2299 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
[*.cs]
# CA1860: Evitar usar el método de extensión "Enumerable.Any()"
dotnet_diagnostic.CA1860.severity = silent

View File

@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CleanArchitecture.Application\CleanArchitecture.Application.csproj" />
<ProjectReference Include="..\CleanArchitecture.Data\CleanArchitecture.Infrastructure.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,6 @@
@CleanArchitecture.API_HostAddress = http://localhost:5124
GET {{CleanArchitecture.API_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@@ -0,0 +1,51 @@
using CleanArchitecture.Application.Features.Streamers.Commands.CreateStreamer;
using CleanArchitecture.Application.Features.Streamers.Commands.DeleteStreamer;
using CleanArchitecture.Application.Features.Streamers.Commands.UpdateStreamer;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net;
namespace CleanArchitecture.API.Controllers
{
[Route("api/v1/[controller]")]
[ApiController]
public class StreamerController : ControllerBase
{
private readonly IMediator mediator;
public StreamerController(IMediator _mediator)
{
mediator = _mediator;
}
[HttpPost(Name = "CreateStreamer")]
[ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
public async Task<ActionResult<int>> CreateStreamer([FromBody] CreateStreamerCommand command)
{
var response = await mediator.Send(command);
return Ok(response);
}
[HttpPut(Name = "UpdateStreamer")]
[ProducesResponseType((int)HttpStatusCode.NoContent)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
[ProducesDefaultResponseType]
public async Task<ActionResult> UpdateStreamer([FromBody] UpdateStreamerCommand command)
{
await mediator.Send(command);
return NoContent();
}
[HttpDelete("{id}", Name = "DeleteStreamer")]
[ProducesResponseType((int)HttpStatusCode.NoContent)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
[ProducesDefaultResponseType]
public async Task<ActionResult> DeleteStreamer(int id)
{
var request = new DeleteStreamerCommand() { Id = id };
await mediator.Send(request);
return NoContent();
}
}
}

View File

@@ -0,0 +1,29 @@
using CleanArchitecture.Application.Features.Videos.Queries.GetVideosList;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net;
namespace CleanArchitecture.API.Controllers
{
[Route("api/v1/[controller]")]
[ApiController]
public class VideoController : ControllerBase
{
private readonly IMediator mediator;
public VideoController(IMediator _mediator)
{
mediator = _mediator;
}
[HttpGet("{username}", Name = "GetVideo")]
[ProducesResponseType(typeof(IEnumerable<VideosVm>), (int)HttpStatusCode.OK)]
public async Task<ActionResult<IEnumerable<VideosVm>>> GetVideosByUserName(string username)
{
var query = new GetVideosListQuery(username);
var videos = await mediator.Send(query);
return Ok(videos);
}
}
}

View File

@@ -0,0 +1,23 @@
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@@ -0,0 +1,31 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:32905",
"sslPort": 0
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5124",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

View File

@@ -0,0 +1,24 @@
using CleanArchitecture.Application.Behaviours;
using FluentValidation;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
namespace CleanArchitecture.Application
{
public static class ApplicationServiceRegistration
{
public static IServiceCollection AddApplicationServices(this IServiceCollection services)
{
services.AddAutoMapper(Assembly.GetExecutingAssembly());
services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());
services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(UnhandledExceptionBehaviour<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>));
return services;
}
}
}

View File

@@ -0,0 +1,28 @@
using MediatR;
using Microsoft.Extensions.Logging;
namespace CleanArchitecture.Application.Behaviours
{
public class UnhandledExceptionBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
{
private readonly ILogger<TRequest> logger;
public UnhandledExceptionBehaviour(ILogger<TRequest> _logger)
{
logger = _logger;
}
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
try
{
return await next();
}catch (Exception ex)
{
var requestName = typeof(TRequest).Name;
logger.LogError(ex, "CleanArchitecture Request: Unhandled Exception for Request {Name} {@Request}", requestName, request);
throw;
}
}
}
}

View File

@@ -0,0 +1,32 @@
using ValidationException = CleanArchitecture.Application.Exceptions.ValidationException;
using FluentValidation;
using MediatR;
namespace CleanArchitecture.Application.Behaviours
{
public class ValidationBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
{
private readonly IEnumerable<IValidator<TRequest>> validators;
public ValidationBehaviour(IEnumerable<IValidator<TRequest>> _validators)
{
this.validators = _validators;
}
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
if (validators.Any())
{
var context = new ValidationContext<TRequest>(request);
var validationResults = await Task.WhenAll(validators.Select(v => v.ValidateAsync(context, cancellationToken)));
var failures = validationResults.SelectMany(r => r.Errors).Where(f => f != null).ToList();
if (failures.Any())
{
throw new ValidationException(failures);
}
}
return await next();
}
}
}

View File

@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\CleanArchitecture.Domain\CleanArchitecture.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Features\Streamers\Queries\" />
<Folder Include="Features\Videos\Commands\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="FluentValidation" Version="11.9.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.9.0" />
<PackageReference Include="MediatR" Version="12.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,11 @@
using CleanArchitecture.Application.Models;
namespace CleanArchitecture.Application.Contracts.Infrastructure
{
public interface IEmailService
{
Task<bool> SendEmail(Email email);
}
}

View File

@@ -0,0 +1,25 @@
using CleanArchitecture.Domain.Common;
using System.Linq.Expressions;
namespace CleanArchitecture.Application.Contracts.Persistence
{
public interface IAsyncRepository<T> where T: BaseDomainModel
{
Task<IReadOnlyList<T>> GetAllAsync();
Task<IReadOnlyList<T>> GetAsync(Expression<Func<T, bool>>? predicate);
Task<IReadOnlyList<T>> GetAsync(Expression<Func<T, bool>>? predicate = null,
Func<IQueryable<T>, IOrderedQueryable<T>>? orderBy = null,
string includeString = null,
bool disableTracking = true);
Task<IReadOnlyList<T>> GetAsync(Expression<Func<T,bool>>? predicate = null,
Func<IQueryable<T>, IOrderedQueryable<T>>? orderBy = null,
List<Expression<Func<T, object>>>? includes = null,
bool disableTracking = true);
Task<T> GetByIdAsync(int id);
Task<T> AddAsync(T entity);
Task<T> UpdateAsync(T entity);
Task DeleteAsync(T entity);
}
}

View File

@@ -0,0 +1,14 @@
using CleanArchitecture.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CleanArchitecture.Application.Contracts.Persistence
{
public interface IStreamerRepository: IAsyncRepository<Streamer>
{
}
}

View File

@@ -0,0 +1,10 @@
using CleanArchitecture.Domain;
namespace CleanArchitecture.Application.Contracts.Persistence
{
public interface IVideoRepository : IAsyncRepository<Video>
{
Task<Video> GetVideoByNombre(string nombreVideo);
Task<IEnumerable<Video>> GetVideoByUserName(string userName);
}
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CleanArchitecture.Application.Exceptions
{
public class NotFoundException: ApplicationException
{
public NotFoundException(string name, object key): base($"Entity \"{name}\" ({key}) not found.")
{
}
}
}

View File

@@ -0,0 +1,18 @@
using FluentValidation.Results;
namespace CleanArchitecture.Application.Exceptions
{
public class ValidationException: ApplicationException
{
public ValidationException() : base("You have 1 or more validation errors")
{
Errors = new Dictionary<string, string[]>();
}
public ValidationException(IEnumerable<ValidationFailure> failures): this()
{
Errors = failures.GroupBy(e=>e.PropertyName, e => e.ErrorMessage).
ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray());
}
public IDictionary<string, string[]> Errors { get; }
}
}

View File

@@ -0,0 +1,10 @@
using MediatR;
namespace CleanArchitecture.Application.Features.Streamers.Commands.CreateStreamer
{
public class CreateStreamerCommand : IRequest<int>
{
public string Nombre { get; set; } = string.Empty;
public string Url { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,48 @@
using AutoMapper;
using CleanArchitecture.Application.Contracts.Infrastructure;
using CleanArchitecture.Application.Contracts.Persistence;
using CleanArchitecture.Application.Models;
using CleanArchitecture.Domain;
using MediatR;
using Microsoft.Extensions.Logging;
namespace CleanArchitecture.Application.Features.Streamers.Commands.CreateStreamer
{
public class CreateStreamerCommandHandler(IStreamerRepository _streamerRepository, IMapper _mapper,
IEmailService _emailService, ILogger<CreateStreamerCommandHandler> _logger) :
IRequestHandler<CreateStreamerCommand, int>
{
private readonly IStreamerRepository streamerRepository = _streamerRepository;
private readonly IMapper mapper = _mapper;
private readonly IEmailService emailService = _emailService;
private readonly ILogger<CreateStreamerCommandHandler> logger = _logger;
public async Task<int> Handle(CreateStreamerCommand request, CancellationToken cancellationToken)
{
var streamerEntity = mapper.Map<Streamer>(request);
var newStreamer = await streamerRepository.AddAsync(streamerEntity);
logger.LogInformation($"Streamer {newStreamer.Id} is successfully created.");
await SendEmail(newStreamer);
return newStreamer.Id;
}
private async Task SendEmail(Streamer streamer)
{
var email = new Email()
{
To = "alejandro@asarmiento.es",
Body = $"Nueva compañia de streamer fue creada. Id: {streamer.Id}",
Subject = "Mensaje de alerta"
};
try
{
await emailService.SendEmail(email);
}
catch (Exception ex)
{
logger.LogError($"Ha ocurrido un error al enviar el email. Error: {ex.Message}");
}
}
}
}

View File

@@ -0,0 +1,18 @@
using FluentValidation;
namespace CleanArchitecture.Application.Features.Streamers.Commands.CreateStreamer
{
public class CreateStreamerCommandValidator : AbstractValidator<CreateStreamerCommand>
{
public CreateStreamerCommandValidator()
{
RuleFor(p => p.Nombre)
.NotEmpty().WithMessage("{Nombre} is required.")
.NotNull()
.MaximumLength(50).WithMessage("{Nombre} must not exceed 50 characters.");
RuleFor(p => p.Url)
.NotEmpty().WithMessage("{Url} is required.");
}
}
}

View File

@@ -0,0 +1,9 @@
using MediatR;
namespace CleanArchitecture.Application.Features.Streamers.Commands.DeleteStreamer
{
public class DeleteStreamerCommand: IRequest<Unit>
{
public int Id { get; set; }
}
}

View File

@@ -0,0 +1,38 @@
using AutoMapper;
using CleanArchitecture.Application.Contracts.Persistence;
using CleanArchitecture.Application.Exceptions;
using CleanArchitecture.Domain;
using MediatR;
using Microsoft.Extensions.Logging;
namespace CleanArchitecture.Application.Features.Streamers.Commands.DeleteStreamer
{
public class DeleteStreamerCommandHandler : IRequestHandler<DeleteStreamerCommand, Unit>
{
private readonly IStreamerRepository streamerRepository;
private readonly IMapper mapper;
private readonly ILogger<DeleteStreamerCommandHandler> logger;
public DeleteStreamerCommandHandler(IStreamerRepository streamerRepository, IMapper mapper, ILogger<DeleteStreamerCommandHandler> logger)
{
this.streamerRepository = streamerRepository;
this.mapper = mapper;
this.logger = logger;
}
public async Task<Unit> Handle(DeleteStreamerCommand request, CancellationToken cancellationToken)
{
var streamerToDelete = await streamerRepository.GetByIdAsync(request.Id);
if (streamerToDelete == null)
{
logger.LogError($"Streamer with id {request.Id} not found.");
throw new NotFoundException(nameof(Streamer), request.Id);
}
await streamerRepository.DeleteAsync(streamerToDelete);
logger.LogInformation($"Streamer {streamerToDelete.Id} is successfully deleted.");
return Unit.Value;
}
}
}

View File

@@ -0,0 +1,11 @@
using MediatR;
namespace CleanArchitecture.Application.Features.Streamers.Commands.UpdateStreamer
{
public class UpdateStreamerCommand : IRequest<Unit>
{
public int Id { get; set; }
public string Nombre { get; set; } = string.Empty;
public string Url { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,42 @@
using AutoMapper;
using CleanArchitecture.Application.Contracts.Persistence;
using CleanArchitecture.Application.Exceptions;
using CleanArchitecture.Domain;
using MediatR;
using Microsoft.Extensions.Logging;
namespace CleanArchitecture.Application.Features.Streamers.Commands.UpdateStreamer
{
public class UpdateStreamerCommandHandler : IRequestHandler<UpdateStreamerCommand, Unit>
{
private readonly IStreamerRepository streamerRepository;
private readonly IMapper mapper;
private readonly ILogger<UpdateStreamerCommandHandler> logger;
public UpdateStreamerCommandHandler(IStreamerRepository streamerRepository,
IMapper mapper, ILogger<UpdateStreamerCommandHandler> logger)
{
this.streamerRepository = streamerRepository;
this.mapper = mapper;
this.logger = logger;
}
public async Task<Unit> Handle(UpdateStreamerCommand request, CancellationToken cancellationToken)
{
var streamerToUpdate = await streamerRepository.GetByIdAsync(request.Id);
if(streamerToUpdate == null)
{
logger.LogError($"Streamer with id {request.Id} not found.");
throw new NotFoundException(nameof(Streamer), request.Id);
}
mapper.Map(request, streamerToUpdate, typeof(UpdateStreamerCommand), typeof(Streamer));
await streamerRepository.UpdateAsync(streamerToUpdate);
logger.LogInformation($"Streamer {streamerToUpdate.Id} is successfully updated.");
return Unit.Value;
}
}
}

View File

@@ -0,0 +1,25 @@
using FluentValidation;
namespace CleanArchitecture.Application.Features.Streamers.Commands.UpdateStreamer
{
public class UpdateStreamerCommandValidator: AbstractValidator<UpdateStreamerCommand>
{
public UpdateStreamerCommandValidator()
{
RuleFor(x=>x.Nombre)
.NotEmpty().WithMessage("{Nombre} is required.")
.NotNull()
.MaximumLength(50).WithMessage("{Nombre} must not exceed 50 characters.");
RuleFor(x => x.Url)
.NotEmpty().WithMessage("{Url} is required.")
.NotNull();
RuleFor(x => x.Id)
.NotEmpty().WithMessage("{Id} is required.")
.NotNull();
}
}
}

View File

@@ -0,0 +1,10 @@
using MediatR;
namespace CleanArchitecture.Application.Features.Videos.Queries.GetVideosList
{
public class GetVideosListQuery(string _UserName) :
IRequest<List<VideosVm>>
{
public string UserName { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,20 @@
using AutoMapper;
using CleanArchitecture.Application.Contracts.Persistence;
using MediatR;
namespace CleanArchitecture.Application.Features.Videos.Queries.GetVideosList
{
public class GetVideosListQueryHandler(IVideoRepository _videoRepository, IMapper _mapper) :
IRequestHandler<GetVideosListQuery, List<VideosVm>>
{
private readonly IVideoRepository videoRepository = _videoRepository;
private readonly IMapper mapper = _mapper;
public async Task<List<VideosVm>> Handle(GetVideosListQuery request, CancellationToken cancellationToken)
{
var videoList = await videoRepository.GetVideoByNombre(request.UserName);
return mapper.Map<List<VideosVm>>(videoList);
}
}
}

View File

@@ -0,0 +1,8 @@
namespace CleanArchitecture.Application.Features.Videos.Queries.GetVideosList
{
public class VideosVm
{
public string? Nombre { get; set; }
public int StreamerId { get; set; }
}
}

View File

@@ -0,0 +1,17 @@
using AutoMapper;
using CleanArchitecture.Application.Features.Streamers.Commands.CreateStreamer;
using CleanArchitecture.Application.Features.Videos.Queries.GetVideosList;
using CleanArchitecture.Domain;
namespace CleanArchitecture.Application.Mappings
{
public class MappingProfile: Profile
{
public MappingProfile()
{
CreateMap<Video, VideosVm>();
CreateMap<CreateStreamerCommand, Streamer>();
}
}
}

View File

@@ -0,0 +1,9 @@
namespace CleanArchitecture.Application.Models
{
public class Email
{
public string? To { get; set; }
public string? Subject { get; set; }
public string? Body { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
namespace CleanArchitecture.Application.Models
{
public class EmailSettings
{
public string? ApiKey { get; set; }
public string? FromAddress { get; set; }
public string? FromName { get; set; }
}
}

View File

@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CleanArchitecture.Data\CleanArchitecture.Data.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,114 @@
using CleanArchitecture.Data;
using CleanArchitecture.Domain;
using Microsoft.EntityFrameworkCore;
ApplicationDbContext context = new();
//await AddNewStreamerWithVideo();
//await NewActorWithVideo();
await AddNewDirectorWithVideo();
//await QueryFilter();
//await QueryMethods();
async Task AddNewStreamerWithVideo()
{
var pantaya = new Streamer
{
Nombre = "Pantaya",
Url = "https://www.pantaya.com"
};
var hungerGames = new Video
{
Nombre = "Hunger Games",
Streamer = pantaya
};
await context.Videos.AddAsync(hungerGames);
await context.SaveChangesAsync();
}
async Task NewActorWithVideo()
{
var actor = new Actor
{
Nombre = "Jennifer",
Apellido = "Lawrence"
};
var hungerGames = await context.Videos.FirstOrDefaultAsync(v => v.Nombre == "Hunger Games");
var videoActor = new VideoActor
{
Actor = actor,
Video = hungerGames
};
await context.VideoActor.AddAsync(videoActor);
await context.SaveChangesAsync();
}
async Task AddNewDirectorWithVideo()
{
var hungerGames = await context.Videos.FirstOrDefaultAsync(v => v.Nombre == "Hunger Games");
var director = new Director
{
Nombre = "Gary",
Apellido = "Ross",
Video = hungerGames
};
hungerGames!.Director = director;
await context.SaveChangesAsync();
}
async Task QueryFilter()
{
Console.WriteLine($"Ingrese una compañia de streaming");
var streamerCompany = Console.ReadLine();
var streamers = await context.Streamers.Where(s => s.Nombre! == streamerCompany).ToListAsync();
if (streamers != null && streamers.Any())
{
streamers.ForEach(s => Console.WriteLine(s.Nombre));
}
else
{
var streamers2 = await context.Streamers.Where(s => s.Nombre!.Contains(streamerCompany!)).AsNoTracking().ToListAsync();
streamers2.ForEach(s => Console.WriteLine(s.Nombre));
}
Console.WriteLine("FIN");
Console.WriteLine("Presione una tecla para continuar");
Console.ReadKey();
Console.Clear();
await QueryFilter();
}
async Task QueryMethods()
{
var streamerDB = context.Streamers;
var streamers1 = await streamerDB.Where(x => x.Nombre!.Contains("a")).FirstOrDefaultAsync();
Console.WriteLine($"WhereFirstOrDefault -> {streamers1?.Nombre}");
var streamers2 = await streamerDB.Where(x => x.Nombre!.Contains("a")).FirstOrDefaultAsync();
Console.WriteLine($"WhereFirstOrDefault -> {streamers2?.Nombre}");
var streamers5 = await streamerDB.Where(x => x.Nombre!.Contains("D")).FirstOrDefaultAsync();
Console.WriteLine($"WhereFirstOrDefault -> {streamers5?.Nombre}");
var streamers3 = await streamerDB.FirstOrDefaultAsync(x => x.Nombre!.Contains("a"));
Console.WriteLine($"FirstOrDefault -> {streamers3?.Nombre}");
var singleAsync = await streamerDB.SingleAsync(x => x.Id == 1);
Console.WriteLine($"singleAsync -> {singleAsync.Nombre}");
var singleOrDefaultAsync = await streamerDB.SingleOrDefaultAsync(x => x.Id == 1);
Console.WriteLine($"SingleOrDefaultAsync -> {singleOrDefaultAsync?.Nombre}");
}

View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CleanArchitecture.Application\CleanArchitecture.Application.csproj" />
<ProjectReference Include="..\CleanArchitecture.Domain\CleanArchitecture.Domain.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,73 @@
// <auto-generated />
using CleanArchitecture.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace CleanArchitecture.Data.Migrations
{
[DbContext(typeof(StreamerDbContext))]
[Migration("20240215100525_InitialMigration")]
partial class InitialMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("CleanArchitecture.Domain.Streamer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Nombre")
.HasColumnType("longtext");
b.Property<string>("Url")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("Streamers");
});
modelBuilder.Entity("CleanArchitecture.Domain.Video", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Nombre")
.HasColumnType("longtext");
b.Property<int>("StreamerId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("StreamerId");
b.ToTable("Videos");
});
modelBuilder.Entity("CleanArchitecture.Domain.Video", b =>
{
b.HasOne("CleanArchitecture.Domain.Streamer", "Streamer")
.WithMany()
.HasForeignKey("StreamerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Streamer");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,72 @@
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace CleanArchitecture.Data.Migrations
{
/// <inheritdoc />
public partial class InitialMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterDatabase()
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "Streamers",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Nombre = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
Url = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_Streamers", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "Videos",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Nombre = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
StreamerId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Videos", x => x.Id);
table.ForeignKey(
name: "FK_Videos_Streamers_StreamerId",
column: x => x.StreamerId,
principalTable: "Streamers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_Videos_StreamerId",
table: "Videos",
column: "StreamerId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Videos");
migrationBuilder.DropTable(
name: "Streamers");
}
}
}

View File

@@ -0,0 +1,163 @@
// <auto-generated />
using System;
using CleanArchitecture.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace CleanArchitecture.Data.Migrations
{
[DbContext(typeof(StreamerDbContext))]
[Migration("20240215190923_Second-Migration")]
partial class SecondMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("CleanArchitecture.Domain.Actor", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Apellido")
.HasColumnType("longtext");
b.Property<string>("Nombre")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("Actor");
});
modelBuilder.Entity("CleanArchitecture.Domain.Director", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Apellido")
.HasColumnType("longtext");
b.Property<string>("Nombre")
.HasColumnType("longtext");
b.Property<int>("VideoId")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Director");
});
modelBuilder.Entity("CleanArchitecture.Domain.Streamer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Nombre")
.HasColumnType("longtext");
b.Property<string>("Url")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("Streamers");
});
modelBuilder.Entity("CleanArchitecture.Domain.Video", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int?>("DirectorId")
.HasColumnType("int");
b.Property<string>("Nombre")
.HasColumnType("longtext");
b.Property<int>("StreamerId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DirectorId")
.IsUnique();
b.HasIndex("StreamerId");
b.ToTable("Videos");
});
modelBuilder.Entity("CleanArchitecture.Domain.VideoActor", b =>
{
b.Property<int>("VideoId")
.HasColumnType("int");
b.Property<int>("ActorId")
.HasColumnType("int");
b.HasKey("VideoId", "ActorId");
b.HasIndex("ActorId");
b.ToTable("VideoActor");
});
modelBuilder.Entity("CleanArchitecture.Domain.Video", b =>
{
b.HasOne("CleanArchitecture.Domain.Director", "Director")
.WithOne("Video")
.HasForeignKey("CleanArchitecture.Domain.Video", "DirectorId");
b.HasOne("CleanArchitecture.Domain.Streamer", "Streamer")
.WithMany("Videos")
.HasForeignKey("StreamerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Director");
b.Navigation("Streamer");
});
modelBuilder.Entity("CleanArchitecture.Domain.VideoActor", b =>
{
b.HasOne("CleanArchitecture.Domain.Actor", null)
.WithMany()
.HasForeignKey("ActorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CleanArchitecture.Domain.Video", null)
.WithMany()
.HasForeignKey("VideoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("CleanArchitecture.Domain.Director", b =>
{
b.Navigation("Video");
});
modelBuilder.Entity("CleanArchitecture.Domain.Streamer", b =>
{
b.Navigation("Videos");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,148 @@
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace CleanArchitecture.Data.Migrations
{
/// <inheritdoc />
public partial class SecondMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Videos_Streamers_StreamerId",
table: "Videos");
migrationBuilder.AddColumn<int>(
name: "DirectorId",
table: "Videos",
type: "int",
nullable: true);
migrationBuilder.CreateTable(
name: "Actor",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Nombre = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
Apellido = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_Actor", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "Director",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Nombre = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
Apellido = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
VideoId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Director", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "VideoActor",
columns: table => new
{
VideoId = table.Column<int>(type: "int", nullable: false),
ActorId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_VideoActor", x => new { x.VideoId, x.ActorId });
table.ForeignKey(
name: "FK_VideoActor_Actor_ActorId",
column: x => x.ActorId,
principalTable: "Actor",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_VideoActor_Videos_VideoId",
column: x => x.VideoId,
principalTable: "Videos",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_Videos_DirectorId",
table: "Videos",
column: "DirectorId",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_VideoActor_ActorId",
table: "VideoActor",
column: "ActorId");
migrationBuilder.AddForeignKey(
name: "FK_Videos_Director_DirectorId",
table: "Videos",
column: "DirectorId",
principalTable: "Director",
principalColumn: "Id");
migrationBuilder.AddForeignKey(
name: "FK_Videos_Streamers_StreamerId",
table: "Videos",
column: "StreamerId",
principalTable: "Streamers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Videos_Director_DirectorId",
table: "Videos");
migrationBuilder.DropForeignKey(
name: "FK_Videos_Streamers_StreamerId",
table: "Videos");
migrationBuilder.DropTable(
name: "Director");
migrationBuilder.DropTable(
name: "VideoActor");
migrationBuilder.DropTable(
name: "Actor");
migrationBuilder.DropIndex(
name: "IX_Videos_DirectorId",
table: "Videos");
migrationBuilder.DropColumn(
name: "DirectorId",
table: "Videos");
migrationBuilder.AddForeignKey(
name: "FK_Videos_Streamers_StreamerId",
table: "Videos",
column: "StreamerId",
principalTable: "Streamers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}

View File

@@ -0,0 +1,215 @@
// <auto-generated />
using System;
using CleanArchitecture.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace CleanArchitecture.Data.Migrations
{
[DbContext(typeof(StreamerDbContext))]
[Migration("20240215201317_BaseDomainModelUpdate")]
partial class BaseDomainModelUpdate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("CleanArchitecture.Domain.Actor", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Apellido")
.HasColumnType("longtext");
b.Property<string>("CreatedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("CreatedDate")
.HasColumnType("datetime(6)");
b.Property<string>("LastModifiedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("LastModifiedDate")
.HasColumnType("datetime(6)");
b.Property<string>("Nombre")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("Actor");
});
modelBuilder.Entity("CleanArchitecture.Domain.Director", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Apellido")
.HasColumnType("longtext");
b.Property<string>("CreatedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("CreatedDate")
.HasColumnType("datetime(6)");
b.Property<string>("LastModifiedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("LastModifiedDate")
.HasColumnType("datetime(6)");
b.Property<string>("Nombre")
.HasColumnType("longtext");
b.Property<int>("VideoId")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Director");
});
modelBuilder.Entity("CleanArchitecture.Domain.Streamer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("CreatedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("CreatedDate")
.HasColumnType("datetime(6)");
b.Property<string>("LastModifiedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("LastModifiedDate")
.HasColumnType("datetime(6)");
b.Property<string>("Nombre")
.HasColumnType("longtext");
b.Property<string>("Url")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("Streamers");
});
modelBuilder.Entity("CleanArchitecture.Domain.Video", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("CreatedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("CreatedDate")
.HasColumnType("datetime(6)");
b.Property<int?>("DirectorId")
.HasColumnType("int");
b.Property<string>("LastModifiedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("LastModifiedDate")
.HasColumnType("datetime(6)");
b.Property<string>("Nombre")
.HasColumnType("longtext");
b.Property<int>("StreamerId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DirectorId")
.IsUnique();
b.HasIndex("StreamerId");
b.ToTable("Videos");
});
modelBuilder.Entity("CleanArchitecture.Domain.VideoActor", b =>
{
b.Property<int>("VideoId")
.HasColumnType("int");
b.Property<int>("ActorId")
.HasColumnType("int");
b.HasKey("VideoId", "ActorId");
b.HasIndex("ActorId");
b.ToTable("VideoActor");
});
modelBuilder.Entity("CleanArchitecture.Domain.Video", b =>
{
b.HasOne("CleanArchitecture.Domain.Director", "Director")
.WithOne("Video")
.HasForeignKey("CleanArchitecture.Domain.Video", "DirectorId");
b.HasOne("CleanArchitecture.Domain.Streamer", "Streamer")
.WithMany("Videos")
.HasForeignKey("StreamerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Director");
b.Navigation("Streamer");
});
modelBuilder.Entity("CleanArchitecture.Domain.VideoActor", b =>
{
b.HasOne("CleanArchitecture.Domain.Actor", "Actor")
.WithMany()
.HasForeignKey("ActorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CleanArchitecture.Domain.Video", "Video")
.WithMany()
.HasForeignKey("VideoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Actor");
b.Navigation("Video");
});
modelBuilder.Entity("CleanArchitecture.Domain.Director", b =>
{
b.Navigation("Video");
});
modelBuilder.Entity("CleanArchitecture.Domain.Streamer", b =>
{
b.Navigation("Videos");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,187 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace CleanArchitecture.Data.Migrations
{
/// <inheritdoc />
public partial class BaseDomainModelUpdate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "CreatedBy",
table: "Videos",
type: "longtext",
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<DateTime>(
name: "CreatedDate",
table: "Videos",
type: "datetime(6)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "LastModifiedBy",
table: "Videos",
type: "longtext",
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<DateTime>(
name: "LastModifiedDate",
table: "Videos",
type: "datetime(6)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "CreatedBy",
table: "Streamers",
type: "longtext",
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<DateTime>(
name: "CreatedDate",
table: "Streamers",
type: "datetime(6)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "LastModifiedBy",
table: "Streamers",
type: "longtext",
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<DateTime>(
name: "LastModifiedDate",
table: "Streamers",
type: "datetime(6)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "CreatedBy",
table: "Director",
type: "longtext",
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<DateTime>(
name: "CreatedDate",
table: "Director",
type: "datetime(6)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "LastModifiedBy",
table: "Director",
type: "longtext",
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<DateTime>(
name: "LastModifiedDate",
table: "Director",
type: "datetime(6)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "CreatedBy",
table: "Actor",
type: "longtext",
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<DateTime>(
name: "CreatedDate",
table: "Actor",
type: "datetime(6)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "LastModifiedBy",
table: "Actor",
type: "longtext",
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<DateTime>(
name: "LastModifiedDate",
table: "Actor",
type: "datetime(6)",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "CreatedBy",
table: "Videos");
migrationBuilder.DropColumn(
name: "CreatedDate",
table: "Videos");
migrationBuilder.DropColumn(
name: "LastModifiedBy",
table: "Videos");
migrationBuilder.DropColumn(
name: "LastModifiedDate",
table: "Videos");
migrationBuilder.DropColumn(
name: "CreatedBy",
table: "Streamers");
migrationBuilder.DropColumn(
name: "CreatedDate",
table: "Streamers");
migrationBuilder.DropColumn(
name: "LastModifiedBy",
table: "Streamers");
migrationBuilder.DropColumn(
name: "LastModifiedDate",
table: "Streamers");
migrationBuilder.DropColumn(
name: "CreatedBy",
table: "Director");
migrationBuilder.DropColumn(
name: "CreatedDate",
table: "Director");
migrationBuilder.DropColumn(
name: "LastModifiedBy",
table: "Director");
migrationBuilder.DropColumn(
name: "LastModifiedDate",
table: "Director");
migrationBuilder.DropColumn(
name: "CreatedBy",
table: "Actor");
migrationBuilder.DropColumn(
name: "CreatedDate",
table: "Actor");
migrationBuilder.DropColumn(
name: "LastModifiedBy",
table: "Actor");
migrationBuilder.DropColumn(
name: "LastModifiedDate",
table: "Actor");
}
}
}

View File

@@ -0,0 +1,212 @@
// <auto-generated />
using System;
using CleanArchitecture.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace CleanArchitecture.Data.Migrations
{
[DbContext(typeof(StreamerDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("CleanArchitecture.Domain.Actor", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Apellido")
.HasColumnType("longtext");
b.Property<string>("CreatedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("CreatedDate")
.HasColumnType("datetime(6)");
b.Property<string>("LastModifiedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("LastModifiedDate")
.HasColumnType("datetime(6)");
b.Property<string>("Nombre")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("Actor");
});
modelBuilder.Entity("CleanArchitecture.Domain.Director", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Apellido")
.HasColumnType("longtext");
b.Property<string>("CreatedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("CreatedDate")
.HasColumnType("datetime(6)");
b.Property<string>("LastModifiedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("LastModifiedDate")
.HasColumnType("datetime(6)");
b.Property<string>("Nombre")
.HasColumnType("longtext");
b.Property<int>("VideoId")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Director");
});
modelBuilder.Entity("CleanArchitecture.Domain.Streamer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("CreatedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("CreatedDate")
.HasColumnType("datetime(6)");
b.Property<string>("LastModifiedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("LastModifiedDate")
.HasColumnType("datetime(6)");
b.Property<string>("Nombre")
.HasColumnType("longtext");
b.Property<string>("Url")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("Streamers");
});
modelBuilder.Entity("CleanArchitecture.Domain.Video", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("CreatedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("CreatedDate")
.HasColumnType("datetime(6)");
b.Property<int?>("DirectorId")
.HasColumnType("int");
b.Property<string>("LastModifiedBy")
.HasColumnType("longtext");
b.Property<DateTime?>("LastModifiedDate")
.HasColumnType("datetime(6)");
b.Property<string>("Nombre")
.HasColumnType("longtext");
b.Property<int>("StreamerId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("DirectorId")
.IsUnique();
b.HasIndex("StreamerId");
b.ToTable("Videos");
});
modelBuilder.Entity("CleanArchitecture.Domain.VideoActor", b =>
{
b.Property<int>("VideoId")
.HasColumnType("int");
b.Property<int>("ActorId")
.HasColumnType("int");
b.HasKey("VideoId", "ActorId");
b.HasIndex("ActorId");
b.ToTable("VideoActor");
});
modelBuilder.Entity("CleanArchitecture.Domain.Video", b =>
{
b.HasOne("CleanArchitecture.Domain.Director", "Director")
.WithOne("Video")
.HasForeignKey("CleanArchitecture.Domain.Video", "DirectorId");
b.HasOne("CleanArchitecture.Domain.Streamer", "Streamer")
.WithMany("Videos")
.HasForeignKey("StreamerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Director");
b.Navigation("Streamer");
});
modelBuilder.Entity("CleanArchitecture.Domain.VideoActor", b =>
{
b.HasOne("CleanArchitecture.Domain.Actor", "Actor")
.WithMany()
.HasForeignKey("ActorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CleanArchitecture.Domain.Video", "Video")
.WithMany()
.HasForeignKey("VideoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Actor");
b.Navigation("Video");
});
modelBuilder.Entity("CleanArchitecture.Domain.Director", b =>
{
b.Navigation("Video");
});
modelBuilder.Entity("CleanArchitecture.Domain.Streamer", b =>
{
b.Navigation("Videos");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,89 @@
using CleanArchitecture.Domain;
using CleanArchitecture.Domain.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
namespace CleanArchitecture.Infrastructure.Persistence
{
public class StreamerDbContext : DbContext
{
public StreamerDbContext(DbContextOptions<StreamerDbContext> options) : base(options)
{
}
//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
//{
// string connectionString = "server=localhost;database=CleanArchitecture;user=root;password=securePassword";
// optionsBuilder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString))
// .LogTo(Console.WriteLine, new[] { DbLoggerCategory.Database.Command.Name }, Microsoft.Extensions.Logging.LogLevel.Information)
// .EnableSensitiveDataLogging();
//}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
foreach(var entry in ChangeTracker.Entries<BaseDomainModel>())
{
switch (entry.State)
{
case EntityState.Modified:
entry.Entity.LastModifiedBy = "System";
entry.Entity.LastModifiedDate = DateTime.Now;
break;
case EntityState.Added:
entry.Entity.CreatedDate = DateTime.Now;
entry.Entity.CreatedBy = "System";
break;
case EntityState.Detached:
break;
case EntityState.Unchanged:
break;
case EntityState.Deleted:
break;
default:
break;
}
}
return base.SaveChangesAsync(cancellationToken);
}
protected override void OnModelCreating(ModelBuilder mb)
{
mb.Entity<Streamer>()
.HasMany(x => x.Videos)
.WithOne(x => x.Streamer)
.HasForeignKey(x => x.StreamerId)
.IsRequired()
.OnDelete(DeleteBehavior.Restrict);
mb.Entity<Video>()
.HasMany(x => x.Actores)
.WithMany(x => x.Videos)
.UsingEntity<VideoActor>(
pt => pt.HasKey(t => new { t.VideoId, t.ActorId })
);
mb.Entity<Video>()
.HasOne(v => v.Director) // Navegación desde Video a Director
.WithOne(d => d.Video) // Navegación inversa desde Director a Video
.HasForeignKey<Director>(d => d.VideoId); // Especifica que la propiedad VideoId en Director es la clave foránea
mb.Entity<Director>()
.HasOne(v => v.Video) // Navegación desde Video a Director
.WithOne(d => d.Director) // Navegación inversa desde Director a Video
.HasForeignKey<Video>(d => d.DirectorId); // Especifica que la propiedad VideoId en Director es la clave foránea
}
public virtual DbSet<Streamer> Streamers { get; set; }
public virtual DbSet<Video> Videos { get; set; }
public virtual DbSet<Actor> Actor { get; set; }
public virtual DbSet<Director> Director { get; set; }
public virtual DbSet<VideoActor> VideoActor { get; set; }
}
}

View File

@@ -0,0 +1,29 @@
using CleanArchitecture.Domain;
using Microsoft.Extensions.Logging;
namespace CleanArchitecture.Infrastructure.Persistence
{
public class StreamerDbContextSeed
{
public static async Task SeedAsync(StreamerDbContext context, ILogger<StreamerDbContextSeed> logger)
{
if (!context.Streamers.Any())
{
context.AddRange(GetPreconfiguredStreamers());
await context.SaveChangesAsync();
logger.LogInformation("Seed database associated with context {DbContextName} executed", typeof(StreamerDbContext).Name);
}
}
private static IEnumerable<Streamer> GetPreconfiguredStreamers()
{
return new List<Streamer>
{
new Streamer() {CreatedBy = "Alex", Nombre = "Netflix", Url = "https://www.netflix.com/" },
new Streamer() {CreatedBy = "Alex", Nombre = "Amazon Prime", Url = "https://www.primevideo.com/" },
};
}
}
}

View File

@@ -0,0 +1,84 @@
using CleanArchitecture.Application.Contracts.Persistence;
using CleanArchitecture.Domain.Common;
using CleanArchitecture.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;
namespace CleanArchitecture.Infrastructure.Repositories
{
public class RepositoryBase<T> : IAsyncRepository<T> where T : BaseDomainModel
{
protected readonly StreamerDbContext context;
public RepositoryBase(StreamerDbContext _context)
{
context = _context;
}
public async Task<IReadOnlyList<T>> GetAllAsync()
{
return await context.Set<T>().ToListAsync();
}
public async Task<IReadOnlyList<T>> GetAsync(Expression<Func<T, bool>> predicate)
{
return await context.Set<T>().Where(predicate).ToListAsync();
}
public async Task<IReadOnlyList<T>> GetAsync(Expression<Func<T,bool>>? predicate = null,
Func<IQueryable<T>, IOrderedQueryable<T>>? orderBy = null,
string includeString = null,
bool disableTracking = true)
{
IQueryable<T> query = context.Set<T>();
if (disableTracking) query = query.AsNoTracking();
if (!string.IsNullOrWhiteSpace(includeString)) query = query.Include(includeString);
if(predicate!=null) query = query.Where(predicate);
if (orderBy != null)
return await orderBy(query).ToListAsync();
return await query.ToListAsync();
}
public async Task<IReadOnlyList<T>> GetAsync(Expression<Func<T, bool>>? predicate = null,
Func<IQueryable<T>, IOrderedQueryable<T>>? orderBy = null,
List<Expression<Func<T, object>>>? includes = null,
bool disableTracking = true)
{
IQueryable<T> query = context.Set<T>();
if (disableTracking) query = query.AsNoTracking();
if (includes != null) query = includes.Aggregate(query, (current, include) => current.Include(include);
if(predicate != null) query = query.Where(predicate);
if (orderBy!=null)
return await orderBy(query).ToListAsync();
return await query.ToListAsync();
}
public virtual async Task<T> GetByIdAsync(int id)
{
return await context.Set<T>().FindAsync(id);
}
public async Task<T> AddAsync(T entity)
{
context.Set<T>().Add(entity);
await context.SaveChangesAsync();
return entity;
}
public async Task<T> UpdateAsync(T entity)
{
context.Entry(entity).State = EntityState.Modified;
await context.SaveChangesAsync();
return entity;
}
public async Task DeleteAsync(T entity)
{
context.Set<T>().Remove(entity);
await context.SaveChangesAsync();
}
}
}

View File

@@ -0,0 +1,17 @@
using CleanArchitecture.Domain.Common;
namespace CleanArchitecture.Domain
{
public class Actor : BaseDomainModel
{
public Actor()
{
Videos = new HashSet<Video>();
}
public string? Nombre { get; set; }
public string? Apellido { get; set; }
public virtual ICollection<Video>? Videos { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CleanArchitecture.Domain.Common
{
public abstract class BaseDomainModel
{
public int Id { get; set; }
public DateTime? CreatedDate { get; set; }
public string? CreatedBy { get; set; }
public DateTime? LastModifiedDate { get; set; }
public string? LastModifiedBy { get; set; }
}
}

View File

@@ -0,0 +1,41 @@
namespace CleanArchitecture.Domain.Common
{
public abstract class ValueObject
{
protected static bool EqualOperator(ValueObject left, ValueObject right)
{
if (left is null ^ right is null)
{
return false;
}
return ReferenceEquals(left, right) || left.Equals(right);
}
protected static bool NotEqualOperator(ValueObject left, ValueObject right)
{
return !(EqualOperator(left, right));
}
protected abstract IEnumerable<object> GetEqualityComponents();
public override bool Equals(object obj)
{
if (obj == null || obj.GetType() != GetType())
{
return false;
}
var other = (ValueObject)obj;
return this.GetEqualityComponents().SequenceEqual(other.GetEqualityComponents());
}
public override int GetHashCode()
{
return GetEqualityComponents()
.Select(x => x != null ? x.GetHashCode() : 0)
.Aggregate((x, y) => x ^ y);
}
// Other utility methods
}
}

View File

@@ -0,0 +1,13 @@
using CleanArchitecture.Domain.Common;
namespace CleanArchitecture.Domain
{
public class Director : BaseDomainModel
{
public string? Nombre { get; set; }
public string? Apellido { get; set; }
public int VideoId { get; set; }
public virtual Video? Video { get; set; }
}
}

View File

@@ -0,0 +1,12 @@
using CleanArchitecture.Domain.Common;
namespace CleanArchitecture.Domain
{
public class Streamer : BaseDomainModel
{
public string? Nombre { get; set; }
public string? Url { get; set; }
public ICollection<Video>? Videos { get; set; }
}
}

View File

@@ -0,0 +1,22 @@
using CleanArchitecture.Domain.Common;
namespace CleanArchitecture.Domain
{
public class Video : BaseDomainModel
{
public Video()
{
Actores = [];
}
public string? Nombre { get; set; }
public int StreamerId { get; set; }
public virtual Streamer? Streamer { get; set; }
public int? DirectorId { get; set; }
public virtual Director? Director { get; set; }
public virtual ICollection<Actor>? Actores { get; set; }
}
}

View File

@@ -0,0 +1,12 @@
using CleanArchitecture.Domain.Common;
namespace CleanArchitecture.Domain
{
public class VideoActor : BaseDomainModel
{
public int VideoId { get; set; }
public virtual Video? Video { get; set; }
public int ActorId { get; set; }
public virtual Actor? Actor { get; set; }
}
}

View File

@@ -0,0 +1,64 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34525.116
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CleanArchitecture.Infrastructure", "CleanArchitecture.Data\CleanArchitecture.Infrastructure.csproj", "{1EDAC629-3BED-4236-8747-4EA167CCDBE5}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CleanArchitecture.Domain", "CleanArchitecture.Domain\CleanArchitecture.Domain.csproj", "{37738D80-1A9E-4FEE-B711-B031EE9737C2}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{D123D836-8F81-46F5-A58F-E7FB09105777}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "doc", "doc", "{6DB2A458-B7C8-4B27-9AAD-EE869E386BFC}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{BB068D3E-ACDC-4C82-95F5-5368BEEF1CCD}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "API", "API", "{6EB52FD0-D3E0-4D88-BD5B-424229B76BD1}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{8BFA0E48-D4BE-48A4-B625-7FD3C7CBC88F}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Infrastructure", "Infrastructure", "{39B5751D-BEC9-4C98-9183-D5AE52248ABA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CleanArchitecture.API", "CleanArchitecture.API\CleanArchitecture.API.csproj", "{4B1B4D47-84CF-4CAA-9A0A-69D8AC16463E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CleanArchitecture.Application", "CleanArchitecture.Application\CleanArchitecture.Application.csproj", "{B9B096A1-C916-40DF-9F9F-9CF384CC0398}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1EDAC629-3BED-4236-8747-4EA167CCDBE5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1EDAC629-3BED-4236-8747-4EA167CCDBE5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1EDAC629-3BED-4236-8747-4EA167CCDBE5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1EDAC629-3BED-4236-8747-4EA167CCDBE5}.Release|Any CPU.Build.0 = Release|Any CPU
{37738D80-1A9E-4FEE-B711-B031EE9737C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{37738D80-1A9E-4FEE-B711-B031EE9737C2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{37738D80-1A9E-4FEE-B711-B031EE9737C2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{37738D80-1A9E-4FEE-B711-B031EE9737C2}.Release|Any CPU.Build.0 = Release|Any CPU
{4B1B4D47-84CF-4CAA-9A0A-69D8AC16463E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B1B4D47-84CF-4CAA-9A0A-69D8AC16463E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B1B4D47-84CF-4CAA-9A0A-69D8AC16463E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B1B4D47-84CF-4CAA-9A0A-69D8AC16463E}.Release|Any CPU.Build.0 = Release|Any CPU
{B9B096A1-C916-40DF-9F9F-9CF384CC0398}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B9B096A1-C916-40DF-9F9F-9CF384CC0398}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B9B096A1-C916-40DF-9F9F-9CF384CC0398}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B9B096A1-C916-40DF-9F9F-9CF384CC0398}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{1EDAC629-3BED-4236-8747-4EA167CCDBE5} = {39B5751D-BEC9-4C98-9183-D5AE52248ABA}
{37738D80-1A9E-4FEE-B711-B031EE9737C2} = {8BFA0E48-D4BE-48A4-B625-7FD3C7CBC88F}
{6EB52FD0-D3E0-4D88-BD5B-424229B76BD1} = {D123D836-8F81-46F5-A58F-E7FB09105777}
{8BFA0E48-D4BE-48A4-B625-7FD3C7CBC88F} = {D123D836-8F81-46F5-A58F-E7FB09105777}
{39B5751D-BEC9-4C98-9183-D5AE52248ABA} = {D123D836-8F81-46F5-A58F-E7FB09105777}
{4B1B4D47-84CF-4CAA-9A0A-69D8AC16463E} = {6EB52FD0-D3E0-4D88-BD5B-424229B76BD1}
{B9B096A1-C916-40DF-9F9F-9CF384CC0398} = {8BFA0E48-D4BE-48A4-B625-7FD3C7CBC88F}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1D95339D-3ACA-48AD-B094-1C90F6DB327B}
EndGlobalSection
EndGlobal