How to handle Enums in ASP.NET Core Web applications

In this tutorial, we are going to learn how to handle Enum based properties in an ASP.NET Core Web application. For that, we will use a small model named Participant with two string properties Firstname and Lastname as well as with one enum property Gender. The Gender property can have three enumerator values: [Male, Female, Other].

First, create a new ASP.NET Core Web application project:

  1. Start Visual Studio (I used Visual Studio 2017 15.9.9)
  2. Select File -> New -> Project…
  3. In the New Project window select Visual C# -> .NET Core -> ASP.NET Core Web Application
  4. Select a folder you want to create your project in, enter the project name and solution name
  5. In the New ASP.NET Core Web Application window, select the Web Application (Model-View-Controller) application type. Additionally, select the ASP.NET Core 2.1 Version. Click OK to confirm your choice.

Next, create a new Model named Participant

  1. In the Solution Explorer right-click on the folder Models and select Add -> Class…
  2. Give it the name Participant and confirm with OK
  3. Replace the content of the Participant.cs file with the following code
public enum Gender
{
    Male,
    Female,
    Other
}

public class Participant
{
    public int Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public Gender Gender { get; set; }
}

We need to create a new database context to be able to add the Participant model to the database.

  1. In the Solution Explorer right-click on the project name and select Add -> Class…
  2. Name the class EnumDBContext and confirm with OK.
  3. Replace the content of the EnumDBContext with the following code.
public class EnumDBContext : DbContext
{
    public EnumDBContext(DbContextOptions<EnumDBContext> options) : base(options) { }

    public DbSet<Participant> Participants { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Participant>()
            .Property(p => p.Gender)
            .HasConversion(
                v => v.ToString(),
                v => (Gender)Enum.Parse(typeof(Gender), v));
    }
}

The class EnumDBContext must be derived from the Microsoft.EntityFrameworkCore.DbContext class. The DBContext class represents a communication session that can be used to read and write entity instances from/to the database.

Next, we declared a DBSet property for the Participant model that represents a database table.

Finally, we override the OnModelCreating method to provide a conversion for the Gender Enum property. The provided conversion converts Enum values to strings that can be rendered in the views and vice versa for saving in the database.

The context we have just created must be registered using dependecy injection in the Startup.cs file.

  1. Double-click on the Startup.cs file to open it.
  2. Add the reference to the Microsoft.EntityFrameworkCore assembly.
using Microsoft.EntityFrameworkCore;

3. Add the following lines to the ConfigureService method. The code configures the communication with the database.

var connection = @"Server=(localdb)\mssqllocaldb;Database=EnumDB;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<EnumDBContext>(options => options.UseSqlServer(connection));

Having this, we can now migrate the Participant entity set to the database. For that, open the Package Manager Console (Tools -> NuGet Package Manager -> Package Manager Console) and execute the following commands.

PM> Add-Migration Initial
PM> Update-Database

Next, we will add the Controller and Views for the Particpant Model.

  1. In the Solution Explorer right-click on the folder Controllers and select Add -> Controller…
  2. In the Add Scaffold select MVC Controller with views, using Entity Framework and click Add
  3. Select Participant in the Model class field
  4. Select EnumDBContext in the Data context class field. Leave the rest as it is and click Add.

This will create the ParticipantsController class (ParticipantsController.cs) as well as Views for the (Create, Delete, Details, Edit, and Index). You won’t be able, however, to create new participants since the created forms in the Create view, cannot render the Enum values. To fix it, open the file Create.cshtml in the folder Views\Participants and replace the following line of code.

<select asp-for="Gender" class="form-control"></select>

With the following code

<select asp-for="Gender" asp-items="Html.GetEnumSelectList<Gender>()" class="form-control">
    <option selected="selected" value="">Please select</option>
</select>

The same changes must be done in the Edit.cshtml file to be able to edit the entries.

Now, if you start the application and call the Participants controller (https://localhost:<your_port>/Participants) the Enum values will be rendered properly and you can create and edit Participant entities with no problems.

You can download the source code for the project here:

https://github.com/asigitov/ASP.NET-Enums

%d bloggers like this: