forked from slavaxom9k/PIBD-23_Fomichev_V.S._MagicCarpet
82 lines
2.9 KiB
C#
82 lines
2.9 KiB
C#
using MagicCarpetContracts.Infrastructure;
|
|
using MagicCarpetContracts.Infrastructure.PostConfigurations;
|
|
using MagicCarpetDatabase.Models;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Linq;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace MagicCarpetDatabase;
|
|
|
|
public class MagicCarpetDbContext(IConfigurationDatabase configurationDatabase) : DbContext
|
|
{
|
|
private readonly IConfigurationDatabase? _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<Client>().HasIndex(x => x.PhoneNumber).IsUnique();
|
|
|
|
modelBuilder.Entity<Sale>()
|
|
.HasOne(e => e.Client)
|
|
.WithMany(e => e.Sales)
|
|
.OnDelete(DeleteBehavior.SetNull);
|
|
|
|
modelBuilder.Entity<Tour>().HasIndex(x => x.TourName).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<SaleTour>().HasKey(x => new { x.SaleId, x.TourId });
|
|
|
|
modelBuilder.Entity<Post>()
|
|
.Property(x => x.Configuration)
|
|
.HasColumnType("jsonb")
|
|
.HasConversion(
|
|
x => SerializePostConfiguration(x),
|
|
x => DeserialzePostConfiguration(x));
|
|
}
|
|
|
|
public DbSet<Client> Clients { get; set; }
|
|
|
|
public DbSet<Post> Posts { get; set; }
|
|
|
|
public DbSet<Tour> Tours { get; set; }
|
|
|
|
public DbSet<TourHistory> TourHistories { get; set; }
|
|
|
|
public DbSet<Salary> Salaries { get; set; }
|
|
|
|
public DbSet<Sale> Sales { get; set; }
|
|
|
|
public DbSet<SaleTour> SaleTours { get; set; }
|
|
|
|
public DbSet<Employee> Employees { 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(TravelAgentPostConfiguration) => JsonConvert.DeserializeObject<TravelAgentPostConfiguration>(jsonString)!,
|
|
nameof(ChiefPostConfiguration) => JsonConvert.DeserializeObject<ChiefPostConfiguration>(jsonString)!,
|
|
_ => JsonConvert.DeserializeObject<PostConfiguration>(jsonString)!,
|
|
};
|
|
}
|