94 lines
No EOL
2.9 KiB
C#
94 lines
No EOL
2.9 KiB
C#
using DrinkRateAPI.DbEntities;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace DrinkRateAPI.Contexts;
|
|
|
|
public class ApplicationDbContext : DbContext
|
|
{
|
|
public DbSet<DbCompany> Companies { get; set; }
|
|
public DbSet<DbCompanyRating> CompanyRatings { get; set; }
|
|
public DbSet<DbCompanyTable> CompanyTables { get; set; }
|
|
public DbSet<DbCompanyTableView> CompanyTableViews { get; set; }
|
|
|
|
public DbSet<DbProduct> Product { get; set; }
|
|
public DbSet<DbProductRating> ProductRating { get; set; }
|
|
public DbSet<DbProductTable> ProductTable { get; set; }
|
|
public DbSet<DbProductTableView> ProductTableView { get; set; }
|
|
|
|
public DbSet<DbUser> Users { get; set; }
|
|
public DbSet<DbUserCompanyTableStat> UserCompanyTableStats { get; set; }
|
|
public DbSet<DbUserProductTableStat> UserProductTableStats { get; set; }
|
|
|
|
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
|
{
|
|
var configuration = new ConfigurationBuilder()
|
|
.SetBasePath(Directory.GetCurrentDirectory())
|
|
.AddJsonFile("appsettings.json")
|
|
.Build();
|
|
|
|
optionsBuilder.UseNpgsql(configuration.GetConnectionString("Local"));
|
|
}
|
|
|
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
|
{
|
|
// Company
|
|
modelBuilder.Entity<DbCompany>(entity =>
|
|
{
|
|
entity.HasKey(c => c.Id);
|
|
|
|
entity.HasMany(c => c.Products)
|
|
.WithOne(p => p.Company)
|
|
.HasForeignKey(p => p.CompanyId);
|
|
|
|
entity.HasMany(c => c.CompanyRatings)
|
|
.WithOne(cr => cr.Company)
|
|
.HasForeignKey(cr => cr.CompanyId);
|
|
|
|
entity.Property(c => c.CompanyName)
|
|
.IsRequired()
|
|
.HasMaxLength(50);
|
|
|
|
entity.HasIndex(c => c.CompanyName)
|
|
.IsUnique();
|
|
|
|
// to do: index by Sum / Count
|
|
});
|
|
|
|
// Company Rating
|
|
modelBuilder.Entity<DbCompanyRating>(entity =>
|
|
{
|
|
entity.HasKey(cr => new { cr.UserId, cr.CompanyId });
|
|
|
|
entity.HasOne(cr => cr.User)
|
|
.WithMany(u => u.CompanyRatings);
|
|
|
|
entity.HasOne(cr => cr.Company)
|
|
.WithMany(c => c.CompanyRatings);
|
|
});
|
|
|
|
// Company Table
|
|
modelBuilder.Entity<DbCompanyTable>(entity =>
|
|
{
|
|
entity.HasKey(ct => ct.Id);
|
|
|
|
entity.HasMany(ct => ct.Companies)
|
|
.WithOne(c => c.CompanyTable)
|
|
.HasForeignKey(c => c.CompanyTableId);
|
|
|
|
entity.HasIndex(ct => ct.CompanyTableName)
|
|
.IsUnique();
|
|
});
|
|
|
|
// Company Table View
|
|
modelBuilder.Entity<DbCompanyTableView>(entity =>
|
|
{
|
|
entity.HasKey(ctv => ctv.Id);
|
|
|
|
entity.HasMany(ctv => ctv.CompanyTables)
|
|
.WithMany();
|
|
|
|
entity.HasMany(ctv => ctv.Users)
|
|
.WithMany(u => u.CompanyTableViews);
|
|
});
|
|
}
|
|
} |