71 lines
2.5 KiB
C#
Executable File
71 lines
2.5 KiB
C#
Executable File
using System.Text.Json;
|
|
using Bogus;
|
|
using Commerce.Contracts.DTOs;
|
|
using Commerce.Domain.Entities;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Commerce.Domain;
|
|
|
|
public class Context : DbContext
|
|
{
|
|
public DbSet<Product> Products { get; set; }
|
|
public DbSet<Category> Categories { get; set; }
|
|
|
|
public Context(DbContextOptions<Context> options)
|
|
: base(options) { }
|
|
|
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
|
{
|
|
base.OnModelCreating(modelBuilder);
|
|
|
|
if (Database.IsNpgsql())
|
|
{
|
|
modelBuilder.Entity<Product>(entity =>
|
|
{
|
|
entity.OwnsMany(e => e.Translations, b =>
|
|
{
|
|
b.ToJson();
|
|
b.OwnsOne(t => t.Info, i =>
|
|
{
|
|
i.OwnsMany(ti => ti.TechnicalDetails);
|
|
});
|
|
});
|
|
});
|
|
|
|
modelBuilder.Entity<Category>(entity =>
|
|
{
|
|
entity.OwnsMany(e => e.Translations, b =>
|
|
{
|
|
b.ToJson();
|
|
b.OwnsOne(t => t.Info, i =>
|
|
{
|
|
i.OwnsMany(ti => ti.TechnicalDetails);
|
|
});
|
|
});
|
|
});
|
|
}
|
|
else
|
|
{
|
|
var productTranslationsConverter = new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<List<ProductTranslation>, string>(
|
|
v => JsonSerializer.Serialize(v, (JsonSerializerOptions?)null),
|
|
v => JsonSerializer.Deserialize<List<ProductTranslation>>(v, (JsonSerializerOptions?)null) ?? new List<ProductTranslation>());
|
|
|
|
var categoryTranslationsConverter = new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<List<CategoryTranslation>, string>(
|
|
v => JsonSerializer.Serialize(v, (JsonSerializerOptions?)null),
|
|
v => JsonSerializer.Deserialize<List<CategoryTranslation>>(v, (JsonSerializerOptions?)null) ?? new List<CategoryTranslation>());
|
|
|
|
modelBuilder.Entity<Product>(entity =>
|
|
{
|
|
entity.Property(e => e.Translations).HasConversion(productTranslationsConverter);
|
|
});
|
|
|
|
modelBuilder.Entity<Category>(entity =>
|
|
{
|
|
entity.Property(e => e.Translations).HasConversion(categoryTranslationsConverter);
|
|
});
|
|
}
|
|
}
|
|
}
|