Great tutorial but I see a couple of issues in using a single context to access the database especially in a very competitive multi-threading environment which would make everything run slow and synchronously even if the calls are asynchronous. So, In order to take advantage of connection pooling (and you should), database connections should be as short lived as possible. Create, use and then immediately destroy. here's an example based on the original examples:
using System;
// Add the missing usings
namespace EFCoreTutorial
{
public class Account
{
[Key]
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
public class DBCtx : DbContext
{
// Account model class created somewhere else
public DbSet<Account> Accounts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySql("Server=localhost;Database=mydatabsename;Uid=root;Pwd=mypassword");
}
}
public class Main : Script
{
[ServerEvent(Event.ResourceStart)]
public void OnResourceStart()
{
using (var ctx = new DBCtx())
{
var playerCount = ctx.Accounts.Count();
NAPI.Util.ConsoleOutput("Total players in the database: " + playerCount);
}
}
[Command("register")]
public void AccountCmdRegister(Client player, string username, string password)
{
// create a new Account object
var account = new Account
{
Username = username,
Password = password
};
using (var ctx = new DBCtx())
{
// Add this account data to the current context
ctx.Accounts.Add(account);
// And finally insert the data into the database
ctx.SaveChanges();
}
player.SendChatMessage("~g~Registration successful!");
}
}
}