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>
</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>

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();
}
}