ITNEXT

ITNEXT is a platform for IT developers & software engineers to share knowledge, connect, collaborate, learn and experience next-gen technologies.

Follow publication

How to use Enums when using Entity Framework Core with C#

Let’s look at a couple of different ways to model enums, and how we can pre-populate our database with these values

Jamie Burns
ITNEXT
Published in
13 min readFeb 23, 2023

A photo of lots of wooden draws
Photo by Jan Antonin Kolar on Unsplash

Entity Framework is great.

It’s not ideal for all situations, but in some cases, it gets a lot of things right.

Recently, I was building a proof of concept for a new system, and this involved two databases. I had a vague idea as to what the database schemas needed to be, but I knew there was going to be a bit of playing around to get it to a point where it works. I considered writing the schema by hand, but realised that maintaining all the relationships and keys when I’m making changes to the schema would be a bit of a headache. Enter Entity Framework!

In case you’ve never used Entity Framework before, it’s an ORM for .NET. You can use it to read and write data from a database using just C#, and you can also use it to generate the schema for that same database, using just what you’ve written in C#.

So that’s what I chose to do — I knew that I could write up the C# classes for what I wanted the data models to look like, and I could generate the database based on that. And if I needed to make changes, I would just update the C# classes and re-generate the database. For me, in this case, this would save me a huge amount of time.

Most of the modelling I used was fairly straight-forward, but there was one aspect that I wanted to make sure I got right: Enums.

Let’s look at the problem I was trying to solve.

The C# Models

I had a handful of classes that needed a ‘type’ property, and this type could be only one of three options. Purely in C#, I would have written the class like this:

public class House
{
public string Name { get; set; }
public HouseSize Size { get; set; }
}

public enum HouseSize
{
Small = 1,
Medium = 2,
Large = 3
}

So I have a House class, that has a size of either Small, Medium or Large.

Pretty simple.

The SQL

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in ITNEXT

ITNEXT is a platform for IT developers & software engineers to share knowledge, connect, collaborate, learn and experience next-gen technologies.

Written by Jamie Burns

Software Engineer, founder of Bungalow64 Technologies