The playthroughs are going well and the bugs have been worked out. It’s time to move on to the next phase of the project and add that SQLite database I’ve been talking about. In this chapter, I’ll spell out what it’s actually going to store. To see the demonstration in action, check out my latest video based on this chapter.
This post is part of a series on creating a roguelike game in C#. For the latest chapters and more information, please visit the Official Project Page on AndrewComeau.com. The current code for this project is also available on Github.
Don’t miss the next chapter! Subscribe for free on Substack to be notified when new chapters are posted.
What data is included?
The Monsters
The list of monsters featured in the game and their stats is currently stored in a static list in the Monster class. This is exactly the kind of data that I’d rather have in a database.
I’ve been making adjustments to the monster stats while working the kinks out of the program and they’re pretty much where they’re going to stay now. Having the definitions in a database instead of a list of constructor declarations will definitely make any future changes easier.
When it comes to translating that data into a table, the constructor actually makes things pretty easy.
Hey, look! All those field names and types spelled right out.
There is some translation needed, though. SQLite doesn’t have data types like MapGlyph. It has five actual storage classes and it maps everything else to one of those classes through type affinity.
- NULL – missing or unknown values
- Integer – Signed whole numbers
- Real – Floating-point
- Text – Text strings and alphanumeric data
- BLOB (Binary Large Object) – Binary data, stored as input
This doesn’t include a specific type for booleans which are stored as Integers, with 0 being False and 1 or everything else being True. Dates are stored as text values in a specific format.
So, I’ll need to break the information down where necessary to save it in these data types and the program will need to convert it back into a usable monster list when it loads it. The program won’t be processing any changes to the monster list; the table will be managed directly with a database shell program during development, in this case the DB Browser for SQLite interface.
The only property in the Monster class that needs extra translation is the DisplayCharacter MapGlyph property I mentioned earlier. This involves the single character used to display the monster on the map which can be stored as text along with foreground and background colors. The names of the colors will need to be stored as text and the program will need to use the Color.FromName() function in order to read them into the list.
The SpecialAttack property is actually the name of a function within the program that carries out whatever special ability the monster has and I’m storing that as text. I’ll have to see how easily C# will accept it when pulled from the database.

The Monster class inherits the Character class which also has a CharacterInventory List property so that monsters can hold on to inventory items. This will have to go into the tables for the saved game although I still gave the Monster table a primary ID field called MonsterID. The tables containing the saved game might need to reference this table.
The Inventory
The Inventory storage is going to be a bit bigger.

The Inventory class has two enumeration types at the beginning which aren’t really a problem; they can be stored as integers to match their values. The program can convert directly when importing them from the database.
public enum InvCategory
{
Food = 0,
Ring = 1,
Scroll = 2,
Wand = 3,
Staff = 4,
Potion = 5,
Armor = 6,
Weapon = 7,
Ammunition = 8,
Amulet = 9,
Gold = 10
}
Just like with the Monster class, the Inventory class uses a MapGlyph type to store the display information for each inventory item and this can also be stored by splitting it into three table fields for character, foreground color and background color.
SQLite also allows for check constraints and foreign keys. The InvCategory enumeration provides categories that the game uses to apply rules to specific kinds of inventory. This enumeration can easily be stored in its own table to restrict the numbers used in the Inventory table and prevent errors. It’s a simple addition with only two fields and a dozen rows to hold the enumeration.
The Inventory table itself needs to have a foreign key linked to this table but there’s a bigger problem; there are 80 inventory items to be entered with a lot of values for each and I’m not doing that manually. I’m not really thrilled about doing it for the monsters table, either, so lets look at another way.
The DB Browser program will import a CSV file to a table either from disk or from the computer’s memory, so I copied the list of inventory templates into Excel and made some adjustments until I had a nice spreadsheet of templates with their properties. This included breaking the MapGlyph referenced into three columns for display character, foreground and background colors. You can see the process in the video.
Then I just needed to import it into the DB Browser to a new table.
This gave me a nicely populated table for Inventory with just a few manual edits because DB Browser didn’t recognize all the ASCII characters that were being used as display characters.
I noticed afterward that I left the text descriptions of the inventory Template enumeration instead of replacing them with the numbers. It was a toss-up whether to go back and fix it but I decided to leave the descriptions in there. They’re easier to read at a glance and the C# code can always translate them back by testing to see if the enumeration includes the description.
Enum.TryParse<InvTemplateID>("ScrollOfIdentify", true, InvTemplateID result)
After that, DB Browser makes it simple to add a foreign key to Inventory, referencing the CategoryID field in InvCategories and ensuring that the InvCategory field in the Inventory table cannot hold any value that isn’t listed there.
I liked the way this worked so much that I went back and re-created the Monsters table by running the data through Excel and importing it from memory. Again, you can see this in the video.
There’s plenty of room for more …
There’s more that will go into the database. There’s even room for debate on what should go in there.
- The player’s saved game will include a few tables for the current map, the player’s profile and all existing inventory. GPT suggested that this is often stored in a temporary file, perhaps JSON, and that’s reasonable enough but it’s just as easy to put it in the database.
- The scoreboard needs to go in there and it’s simple enough for one table but it can wait a little longer.
- I’m playing with the idea of moving some game constants over to the database to allow easier customization of the game experience or multiple difficulty levels.
For now, I’m going to stick with the monsters and inventory and actually get the database into the project; I can add the rest later. Ongoing changes to the database are as much a part of the project as changes to the code, after all.
Adding the database
The next step is to actually add the database to the project which simply means –
- Creating a Data folder under the project in Visual Studio
- Adding the database as an existing object
- Setting Build Action to “Content”
- Setting Copy to Output Directory to “Copy if newer”
Adding EntityFramework
Entity Framework is an ORM (Object Relational Mapper) that creates the classes based on your tables, manages the connection to the database and simplifies the code associated with moving the data between the database and program.
The packages for Entity Framework are added through the package manager in Visual Studio (Tools → Manage NuGet Packages for Solution). I’m adding three to this project.
- Microsoft.EntityFrameworkCore.Design
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.EntityFrameworkCore.SQLite

Since, this project is in .NET 9.0, I’m using the latest edition of version 9 for each of these tools for compatibility. After adding the packages, you’ll be able to see them listed under the Dependencies menu in the Solution Explorer.
With the database in place and the packages installed, the next step was to run the Scaffold-DbContext command in the Package Manger Console (Tools -> Nuget Package Manager -> Package Manger Console) and let it generate the context and model classes based on the database file.
Scaffold-DbContext "Datasource=.\Data\Rogue.db" Microsoft.EntityFrameworkCore.Sqlite -ContextDir Data -OutputDir Models
The RogueContext.cs class identifies the tables that exist in the database and maps the model classes to them. It also provides connection information for the database, although it does warn to move authentication information elsewhere. In this case, there is no password on the database so I don’t mind leaving it right there.
If I make changes to the structure of the database, updating it is as simple as putting the new database in the project folder and running the same Scaffold-DbContext command again, except with the -Force switch on the end of it.
The scaffolding process also creates a model class for each table which maps out the fields and indexes in the table. Unfortunately, I named the tables the same as the classes that I already had in the project, i.e. Monster and Inventory, so now I have model classes with the same names under a different namespace. A GlobalUsings.cs class under the main project folder took care of that and provided aliases for the different classes.
global using GameMonster = RogueGame.Monster;
global using DbMonster = RogueCSharp.Models.Monster;
global using GameInventory = RogueGame.Inventory;
global using DbInventory = RogueCSharp.Models.Inventory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RogueCSharp
{
internal class GlobalUsings
{
}
}
Another problem I ran into was the quotes around single characters like the DisplayCharacter. I had to remove those but it was no big deal. The double quotes around item names, etc. will probably need to go.
The code
I like to have a central data class that handles requests and writes to the database so I decided to add a DataMgmt class to the Data directory with the RogueContext.cs class. An instance of the context class is necessary to communicate with the database so I decided to add a single instance at class level.
internal class DataMgmt
{
RogueContext rcData = new RogueContext();
public ImmutableList<Models.Monster> GetMonsterList()
{
rcData.Monsters.Load();
ImmutableList<Models.Monster> MonsterList = rcData.Monsters.Local.ToImmutableList();
return MonsterList;
}
}
The first function in DataMgmt.cs was to retrieve the list of monsters so that I can load it as needed. The list is actually a list of rows defined by the Monster model class. Given all the things that can go wrong at this point, it’s definitely time to start adding some error handling but I’ll see if I can get things working first.
I thought about creating a query in the database that served up an identical row to the game’s original Monster class that could be automatically converted to a monster object, except … no, there’s that MapGlyph object that I had to split into three table columns. That has to be reassembled when retrieved from the database.
The Monster class was maintaining the list of Monster templates as a private static list built from a group of Monster declarations. Instead of the list of declarations, I now have a function that populates the list from the new database connection.
public void LoadMonsters()
{
DataMgmt dm = new DataMgmt();
ImmutableList<DbMonster> monsterList = dm.GetMonsterList();
GameMonster gMonster;
foreach (DbMonster monster in monsterList)
{
gMonster = new GameMonster(
monster.CharacterName,
monster.MinStartingHp,
monster.MaxStartingHp,
monster.ArmorClass,
monster.ExpReward,
monster.MinLevel,
monster.MaxLevel,
monster.AppearanceProb,
monster.MinAttackDmg,
monster.MaxAttackDmg,
new MapGlyph(monster.DisplayChar[0], Color.FromName(monster.ForeColor), Color.FromName(monster.BackColor)),
monster.SpecialAttackProb,
monster.SpecialAttack != null ? GetAction(monster.SpecialAttack) : null,
(monster.Aggressive != 0),
monster.Inertia,
(monster.CanRegenerate != 0)
);
monsterInc.Add(gMonster);
}
}
For each instance of the Monster model class in the database list, the function creates a new Monster game object and adds it to the class list.
- The reassembly of the MapGlyph went smoothly although I realized that the single quotes I’d placed around the DisplayCharacter in the database were unnecessary so I removed those.
- C# didn’t want to automatically accept a string value for the name of the delegate function used for the monster’s special attack. In a rare allowance on my part, I turned to ChatGPT and it provided a custom GetAction() function that would accept the string value and convert it.
- Again, SQLite doesn’t have a boolean type so I used the number type and anything not equal to 0 equals True.
private static Func<Monster, Character, int, string>? GetAction(string methodName)
{
var method = typeof(Monster).GetMethod(
methodName,
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Static
);
if (method != null)
return (Func<Monster, Character, int, string>)Delegate.CreateDelegate(
typeof(Func<Monster, Character, int, string>),
method
);
else
return null;
}
All the monsters in a row …
The next issue was that the monsters aren’t loaded at the start of the game the way the Inventory templates are. I dimly remember that I decided to do it that way with the Inventory because of the sheer amount of memory that was being taken up by the 80 inventory templates that were included with every instance of the class and ended up loading recursively. The Monster class didn’t have this issue, probably because its list was static while the Inventory list wasn’t.
Looking at it now, I probably could have avoided a lot of problems and work by making the Inventory list static as well, but what’s done is done.
So, the monster list now needs to be loaded somewhere. I finally decided to create a new constructor for the game’s Monster class that creates a dummy Monster object (honestly, none of them are probably that smart) and allows access to instance methods and the monster list.
public Monster(bool LoadMonsterList)
{
if (LoadMonsterList)
LoadMonsters();
}
Then, I changed the two methods in the MapLevel class that needed to access the Monster list and had them create an instance that would load the list. In the process, I found a third reference to the list that was completely unnecessary and could be removed.
Taking Inventory
Another problem I ran into was that letting DB Browser define the table structure from the CSV data doesn’t guarantee correct settings. It left a bunch of the fields nullable so the scaffolding process translated them to nullable properties which caused problems when writing the import routine to put the values into non-nullable class properties. It also marked a couple of fields like PluralName as numeric, don’t ask me why.
Once those bugs were fixed, loading the inventory was pretty similar to loading the monsters and the game compiled and ran as expected.
If you would like to learn more about SQL and SQLite, please take a moment to check out my latest book on Amazon and Kindle+.











