SharpRSS/SharpRSS.API/Data/DbAccess.cs

48 lines
1.8 KiB
C#

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using SharpRSS.API.Models.Auth;
using ToolQit;
using ToolQit.Logging;
namespace SharpRSS.API.Data
{
public sealed class DbAccess : DbContext
{
public DbAccess(IConfiguration configuration)
{
_log = LogManager.CreateLogger(typeof(DbAccess));
_configuration = configuration;
Database.EnsureCreated();
}
public DbSet<User> Users { get; set; }
private readonly IConfiguration _configuration;
private readonly ILog _log;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string connection = _configuration["DataBase:Connection"] ?? throw new ArgumentNullException(nameof(_configuration), "No connection string in appsettings!");
string server = _configuration["DataBase:Server"] ?? "Unknown";
switch (server)
{
case "MariaDB":
var dbSrvVersion = ServerVersion.AutoDetect(connection);
_log.Information("Server {SrvType} detected, version: {SrvVersion}", dbSrvVersion.Type.ToString(), dbSrvVersion.Version);
optionsBuilder.UseMySql(connection, dbSrvVersion);
break;
default: // TODO: Add more database support.
_log.Warning("No valid db server: {Server}/nSupported db servers: 'MariaDB'", server);
throw new Exception("Database server not specified!");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("srss_user");
base.OnModelCreating(modelBuilder);
}
}
}