2025-12-14 20:24:33 -08:00

79 lines
2.7 KiB
C#

using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Options;
using Org.BouncyCastle.Asn1.Nist;
namespace qtc_api.Data
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public DbSet<User> Users { get; set; }
public DbSet<Room> Rooms { get; set; }
public DbSet<RefreshToken> ValidRefreshTokens { get; set; }
public DbSet<Contact> Contacts { get; set; }
public DbSet<OwnedStoreItem> OwnedStoreItems { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
var dbProvider = Environment.GetEnvironmentVariable("DB_PROVIDER");
var connectionString = Environment.GetEnvironmentVariable("DB_CONNECTION_STRING");
if (dbProvider != null && connectionString != null)
{
switch (dbProvider)
{
case "MySQL":
options.UseMySQL(connectionString);
break;
case "SQLite":
options.UseSqlite(connectionString);
break;
default: throw new Exception("Unsupported Database Provider. Please Check 'DB_PROVIDER' Environment Variable.");
}
} else throw new Exception("Cannot Find Environment Variables 'DB_PROVIDER' And 'DB_CONNECTION_STRING'. Please Check Environment.");
}
protected override void OnModelCreating(ModelBuilder builder)
{
// Users
builder.Entity<User>().HasMany(e => e.ContactsList);
builder.Entity<User>().HasMany(e => e.ContactsMade);
builder.Entity<User>().HasMany(e => e.OwnedStoreItems);
builder.Entity<User>()
.Property<string>("_tagString")
.HasColumnName("Tags");
// Rooms (no relations)
builder.Entity<Room>();
// Refresh Tokens
builder.Entity<RefreshToken>().HasOne(e => e.User)
.WithMany(e => e.RefreshTokens)
.HasForeignKey(e => e.UserID);
// Contacts
builder.Entity<Contact>().HasOne(e => e.Owner)
.WithMany(e => e.ContactsMade)
.HasForeignKey(e => e.OwnerId);
builder.Entity<Contact>().HasOne(e => e.User)
.WithMany(e => e.ContactsList)
.HasForeignKey(e => e.UserId);
// Purchased Store Items
builder.Entity<OwnedStoreItem>().HasOne(e => e.User)
.WithMany(e => e.OwnedStoreItems)
.HasForeignKey(e => e.UserId);
}
}
}