Files
Pibd-21_Semin_D.A._SmallSof…/SmallSoftwareProject/SmallSoftwareDatabase/SmallSoftwareDbContext.cs
2025-04-24 00:06:05 +04:00

69 lines
3.1 KiB
C#

using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SmallSoftwareContracts.Infrastructure;
using SmallSoftwareContracts.Infrastructure.PostConfigurations;
using SmallSoftwareDatabase.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmallSoftwareDatabase;
internal class SmallSoftwareDbContext : DbContext
{
private readonly IConfigurationDatabase? _configurationDatabase;
public SmallSoftwareDbContext(IConfigurationDatabase configurationDatabase)
{
_configurationDatabase = configurationDatabase;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(_configurationDatabase?.ConnectionString, o => o.SetPostgresVersion(12, 2));
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Manufacturer>().HasIndex(x => x.ManufacturerName).IsUnique();
modelBuilder.Entity<Post>().HasIndex(e => new { e.PostName, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<Post>().HasIndex(e => new { e.PostId, e.IsActual })
.IsUnique()
.HasFilter($"\"{nameof(Post.IsActual)}\" = TRUE");
modelBuilder.Entity<Software>().HasIndex(x => new { x.SoftwareName, x.IsDeleted })
.IsUnique()
.HasFilter($"\"{nameof(Software.IsDeleted)}\" = FALSE");
modelBuilder.Entity<Software>()
.HasOne(e => e.Manufacturer)
.WithMany(e => e.Softwares)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<InstallationRequest>().HasKey(x => new { x.RequestId, x.SoftwareId });
modelBuilder.Entity<Worker>().Property(x => x.Configuration).HasColumnType("jsonb").HasConversion(
x => SerializePostConfiguration(x),
x => DeserialzePostConfiguration(x)
);
}
public DbSet<Manufacturer> Manufacturers { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Software> Softwares { get; set; }
public DbSet<SoftwareHistory> SoftwareHistories { get; set; }
public DbSet<Salary> Salaries { get; set; }
public DbSet<Request> Requests { get; set; }
public DbSet<InstallationRequest> InstallationRequests { get; set; }
public DbSet<Worker> Workers { get; set; }
private static string SerializePostConfiguration(PostConfiguration postConfiguration) => JsonConvert.SerializeObject(postConfiguration);
private static PostConfiguration DeserialzePostConfiguration(string jsonString) => JToken.Parse(jsonString).Value<string>("Type") switch
{
nameof(CashierPostConfiguration) => JsonConvert.DeserializeObject<CashierPostConfiguration>(jsonString)!,
nameof(SupervisorPostConfiguration) => JsonConvert.DeserializeObject<SupervisorPostConfiguration>(jsonString)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(jsonString)!
};
}