SCHALE.GameServer/SCHALE.Common/Database/SCHALEContext.cs

73 lines
2.7 KiB
C#
Raw Normal View History

2024-04-18 07:12:10 +00:00
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.ValueGeneration;
using MongoDB.EntityFrameworkCore.Extensions;
using SCHALE.Common.Database.Models;
2024-04-25 03:50:09 +00:00
using SCHALE.Common.Database.Models.Game;
2024-04-18 07:12:10 +00:00
namespace SCHALE.Common.Database
{
public class SCHALEContext : DbContext
{
2024-04-25 03:50:09 +00:00
public DbSet<GuestAccount> GuestAccounts { get; set; }
2024-04-18 07:12:10 +00:00
public DbSet<Account> Accounts { get; set; }
public DbSet<Counter> Counters { get; set; }
public DbSet<Player> Players { get; set; }
public Player CurrentPlayer { get { return Players.FirstOrDefault();} } // temp
2024-04-18 07:12:10 +00:00
public SCHALEContext(DbContextOptions<SCHALEContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
2024-04-25 03:50:09 +00:00
modelBuilder.Entity<GuestAccount>().Property(x => x.Uid).HasValueGenerator<GuestAccountAutoIncrementValueGenerator>();
modelBuilder.Entity<GuestAccount>().ToCollection("guest_accounts");
2024-04-18 07:12:10 +00:00
modelBuilder.Entity<Account>().ToCollection("accounts");
modelBuilder.Entity<Player>().ToCollection("players");
// attempt to fix MissionProgressDB.Dictionary<long, long> ProgressParameters serialization
modelBuilder.Entity<Player>().Property(e => e.MissionProgressDBs).HasJsonConversion<List<MissionProgressDB>>();
2024-04-25 03:50:09 +00:00
2024-04-18 07:12:10 +00:00
modelBuilder.Entity<Counter>().ToCollection("counters");
}
2024-04-25 03:50:09 +00:00
private class GuestAccountAutoIncrementValueGenerator : AutoIncrementValueGenerator
{
protected override string Collection => "guest_account";
}
2024-04-18 07:12:10 +00:00
2024-04-25 03:50:09 +00:00
private abstract class AutoIncrementValueGenerator : ValueGenerator<uint>
2024-04-18 07:12:10 +00:00
{
2024-04-25 03:50:09 +00:00
protected abstract string Collection { get; }
public override bool GeneratesTemporaryValues => false;
public override uint Next(EntityEntry entry)
2024-04-18 07:12:10 +00:00
{
2024-04-25 03:50:09 +00:00
if (entry.Context is not SCHALEContext)
{
throw new ArgumentNullException($"{nameof(AutoIncrementValueGenerator)} is only implemented for {nameof(SCHALEContext)}");
}
2024-04-18 07:12:10 +00:00
2024-04-25 03:50:09 +00:00
var context = ((SCHALEContext)entry.Context);
var counter = context.Counters.SingleOrDefault(x => x.Id == Collection);
2024-04-18 07:12:10 +00:00
2024-04-25 03:50:09 +00:00
if (counter is null)
{
counter = new Counter() { Id = Collection, Seq = 0 };
context.Add(counter);
}
counter.Seq++;
2024-04-20 05:24:36 +00:00
context.SaveChanges();
2024-04-25 03:50:09 +00:00
return counter.Seq;
2024-04-18 07:12:10 +00:00
}
2024-04-25 03:50:09 +00:00
}
2024-04-18 07:12:10 +00:00
}
}