dal + other

This commit is contained in:
Mikhail Kuznetsov
2023-05-17 16:30:13 +10:00
parent 5338c489aa
commit 868af2dd0e
27 changed files with 346 additions and 20 deletions

View File

@@ -0,0 +1,16 @@
using Microsoft.EntityFrameworkCore;
using PARR.DAL.Models;
namespace PARR.DAL.Context
{
internal class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options) { }
//public DbSet<Test> Tests { get; set; }
//public DbSet<Place> Places { get; set; }
//public DbSet<AreaCategory> AreaCategories { get; set; }
//public DbSet<Area> Areas { get; set; }
}
}

View File

@@ -0,0 +1,29 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using PARR.DAL.Context;
#nullable disable
namespace PARR.DAL.Migrations
{
[DbContext(typeof(DataContext))]
[Migration("20230517062913_init")]
partial class init
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace PARR.DAL.Migrations
{
/// <inheritdoc />
public partial class init : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

View File

@@ -0,0 +1,26 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using PARR.DAL.Context;
#nullable disable
namespace PARR.DAL.Migrations
{
[DbContext(typeof(DataContext))]
partial class DataContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.5")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,11 @@
namespace PARR.DAL.Models.Base
{
public interface IBase
{
Guid Id { get; set; }
DateTimeOffset DateCreated { get; set; }
DateTimeOffset? DateModified { get; set; }
}
}

19
PARR.DAL/Models/Test.cs Normal file
View File

@@ -0,0 +1,19 @@
using PARR.DAL.Models.Base;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace PARR.DAL.Models
{
[Table("Tests")]
public class Test : IBase
{
[Key]
public Guid Id { get; set; }
public DateTimeOffset DateCreated { get; set; }
public DateTimeOffset? DateModified { get; set; }
public required string Name { get; set; }
public string? Description { get; set; }
}
}

View File

@@ -6,4 +6,19 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.4" />
</ItemGroup>
<ItemGroup>
<Folder Include="Contracts\" />
<Folder Include="Services\Implementations\" />
</ItemGroup>
</Project> </Project>

View File

@@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using PARR.DAL.Context;
namespace PARR.DAL
{
public static class ParrDalInstaller
{
public static void InstallDalServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<DataContext>(opt =>
opt.UseNpgsql(configuration.GetConnectionString("DefaultConnection"))
);
//services.AddTransient<ILayerService, LayerService>();
//services.AddTransient<IUsersInLayersService, UsersInLayersService>();
//services.AddTransient<IAreaService, AreaService>();
//services.AddTransient<IAreasInLayerService, AreasInLayerService>();
}
}
}

View File

@@ -0,0 +1,119 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.DAL.Context;
using PARR.DAL.Models.Base;
using PARR.DAL.Services.Interfaces.Base;
namespace PARR.DAL.Services.Abstracts
{
internal abstract class BaseService<T> : IBaseService<T> where T : class, IBase
{
private readonly ILogger<BaseService<T>> logger;
protected abstract DbSet<T> EntitySet { get; }
protected abstract DataContext EntitiContext { get; }
public BaseService(ILogger<BaseService<T>> logger)
{
this.logger = logger;
}
public virtual async Task<bool> AddRangeAsync(List<T> objs)
{
objs.ForEach(item => item.DateCreated = DateTimeOffset.UtcNow);
try
{
await EntitySet.AddRangeAsync(objs);
return true;
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при добавлении диапазона в БД.");
return false;
}
}
public async Task<bool> CommitAsync()
{
try
{
await EntitiContext.SaveChangesAsync();
return true;
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при Commit");
return false;
}
}
public virtual async Task<bool> CreateAsync(T obj)
{
obj.DateCreated = DateTimeOffset.UtcNow;
try
{
await EntitySet.AddAsync(obj);
return true;
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при добавлении в БД.");
return false;
}
}
public virtual bool Delete(T obj)
{
try
{
EntitySet.Remove(obj);
return true;
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при удалении из БД.");
return false;
}
}
public virtual async Task<bool> DeleteAsync(Guid id)
{
try
{
var exist = await GetAsync(id);
if (exist == null)
{
logger.LogError($"Ошибка при удалении из БД. Не найдена запись в БД с id: {id}");
return false;
}
EntitySet.Remove(exist);
return true;
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка при удалении из БД.");
return false;
}
}
public virtual IQueryable<T> Get()
{
return EntitySet;
}
public virtual async Task<T?> GetAsync(Guid id)
{
return await EntitySet.FirstOrDefaultAsync(t => t.Id == id);
}
//public virtual IQueryable<T> GetPage(IQueryable<T> query, PaginationFilter paginationFilter)
//{
// int skip = (paginationFilter.PageNumber - 1) * paginationFilter.PageSize;
// return query.Skip(skip).Take(paginationFilter.PageSize);
//}
}
}

View File

@@ -0,0 +1,19 @@
using PARR.DAL.Models.Base;
namespace PARR.DAL.Services.Interfaces.Base
{
public interface IBaseService<T> where T : class, IBase
{
Task<T?> GetAsync(Guid id);
IQueryable<T> Get();
//IQueryable<T> GetPage(IQueryable<T> query, PaginationFilter paginationFilter);
Task<bool> CreateAsync(T obj);
Task<bool> AddRangeAsync(List<T> objs);
Task<bool> DeleteAsync(Guid id);
bool Delete(T obj);
Task<bool> CommitAsync();
}
}

View File

@@ -3,7 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.4.33213.308 VisualStudioVersion = 17.4.33213.308
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PARR_API", "PARR_API\PARR_API.csproj", "{82C57299-DA04-4A99-9C04-614FDDCE7AA1}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PARR.API", "PARR_API\PARR.API.csproj", "{82C57299-DA04-4A99-9C04-614FDDCE7AA1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PARR.DAL", "PARR.DAL\PARR.DAL.csproj", "{CBC557EE-382E-4386-B4D2-2EE3DC9A7CBE}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -15,6 +17,10 @@ Global
{82C57299-DA04-4A99-9C04-614FDDCE7AA1}.Debug|Any CPU.Build.0 = Debug|Any CPU {82C57299-DA04-4A99-9C04-614FDDCE7AA1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{82C57299-DA04-4A99-9C04-614FDDCE7AA1}.Release|Any CPU.ActiveCfg = Release|Any CPU {82C57299-DA04-4A99-9C04-614FDDCE7AA1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{82C57299-DA04-4A99-9C04-614FDDCE7AA1}.Release|Any CPU.Build.0 = Release|Any CPU {82C57299-DA04-4A99-9C04-614FDDCE7AA1}.Release|Any CPU.Build.0 = Release|Any CPU
{CBC557EE-382E-4386-B4D2-2EE3DC9A7CBE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CBC557EE-382E-4386-B4D2-2EE3DC9A7CBE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CBC557EE-382E-4386-B4D2-2EE3DC9A7CBE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CBC557EE-382E-4386-B4D2-2EE3DC9A7CBE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@@ -1,4 +1,4 @@
namespace PARR_API.Contracts.V1 namespace PARR.API.Contracts.V1
{ {
// https://tproger.ru/translations/luchshie-praktiki-razrabotki-rest-api-20-sovetov/ // https://tproger.ru/translations/luchshie-praktiki-razrabotki-rest-api-20-sovetov/

View File

@@ -1,6 +1,6 @@
using PARR_API.Controllers.V1.Base; using PARR.API.Controllers.V1.Base;
namespace PARR_API.Controllers.V1 namespace PARR.API.Controllers.V1
{ {
public class ApiStatusController : BaseApiController public class ApiStatusController : BaseApiController
{ {

View File

@@ -1,6 +1,6 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace PARR_API.Controllers.V1.Base namespace PARR.API.Controllers.V1.Base
{ {
[ApiController] [ApiController]
public class BaseApiController : ControllerBase public class BaseApiController : ControllerBase

View File

@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;
namespace PARR.API.Controllers.V1
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
}

View File

@@ -1,7 +1,7 @@
using PARR_API.Services.Implementations; using PARR.API.Services.Implementations;
using PARR_API.Services.Interfaces; using PARR.API.Services.Interfaces;
namespace PARR_API.Installers namespace PARR.API.Installers
{ {
/// <summary> /// <summary>
/// Самописные сервисы которые используются для АПИ /// Самописные сервисы которые используются для АПИ

View File

@@ -1,6 +1,6 @@
using PARR_API.Settings; using PARR.API.Settings;
namespace PARR_API.Installers namespace PARR.API.Installers
{ {
public static class CorsInstaller public static class CorsInstaller
{ {

View File

@@ -1,4 +1,4 @@
namespace PARR_API.Installers namespace PARR.API.Installers
{ {
/// <summary> /// <summary>
/// Биндинги из конфига appsettings /// Биндинги из конфига appsettings

View File

@@ -1,7 +1,7 @@
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using System.Reflection; using System.Reflection;
namespace PARR_API.Installers namespace PARR.API.Installers
{ {
public static class SwaggerInstaller public static class SwaggerInstaller
{ {

View File

@@ -1,6 +1,6 @@
using AutoMapper; using AutoMapper;
namespace PARR_API.MappingProfiles namespace PARR.API.MappingProfiles
{ {
public class DomainToResponseProfile : Profile public class DomainToResponseProfile : Profile
{ {

View File

@@ -1,6 +1,6 @@
using AutoMapper; using AutoMapper;
namespace PARR_API.MappingProfiles namespace PARR.API.MappingProfiles
{ {
public class RequestToDomainProfile : Profile public class RequestToDomainProfile : Profile
{ {

View File

@@ -19,6 +19,10 @@
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" /> <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.5.2" /> <PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.5.2" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.5" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" /> <PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="7.0.0" /> <PackageReference Include="Serilog.Extensions.Hosting" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" /> <PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
@@ -33,4 +37,8 @@
<Folder Include="Validators\" /> <Folder Include="Validators\" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PARR.DAL\PARR.DAL.csproj" />
</ItemGroup>
</Project> </Project>

View File

@@ -1,5 +1,6 @@
using FluentValidation; using FluentValidation;
using PARR_API.Installers; using PARR.API.Installers;
using PARR.DAL;
using Serilog; using Serilog;
using System.Reflection; using System.Reflection;
@@ -13,6 +14,7 @@ builder.Host.UseSerilog((context, config) =>
}); });
// Add services to the container. // Add services to the container.
builder.Services.InstallDalServices(builder.Configuration);
builder.Services.InstallApiServices(builder.Configuration); builder.Services.InstallApiServices(builder.Configuration);
builder.Services.InstallSettings(builder.Configuration); builder.Services.InstallSettings(builder.Configuration);
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

View File

@@ -1,6 +1,6 @@
using PARR_API.Services.Interfaces; using PARR.API.Services.Interfaces;
namespace PARR_API.Services.Implementations namespace PARR.API.Services.Implementations
{ {
public class UriService : IUriService public class UriService : IUriService
{ {

View File

@@ -1,4 +1,4 @@
namespace PARR_API.Services.Interfaces namespace PARR.API.Services.Interfaces
{ {
public interface IUriService public interface IUriService
{ {

View File

@@ -1,4 +1,4 @@
namespace PARR_API.Settings namespace PARR.API.Settings
{ {
public class CorsSettings public class CorsSettings
{ {

View File

@@ -1,6 +1,6 @@
{ {
"ConnectionStrings": { "ConnectionStrings": {
"DefaultConnection": "Server=10.99.253.184;Database=geo;User Id=app_geo; Password=Khdlifg(G875904HJFfd@3;" "DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;"
}, },
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {