When dealing with databases, there are times when you want a column to only allow certain values. When using EF Core, the easiest way to accomplish this goal is to use an enum as the type for the property.

In this post, we will add a new column to an entity that is of an enum type, set the default value, and create the migration script.

This post uses the sample code from our previous post. You can download this code here

The first thing we need to do is create an enum.

  1. Create a file name Status.cs

    Status.cs
    
  2. To the Status.cs add the following code to create our enum

    namespace EntityFrameworkExample;
    
    public enum Status
    {
        Draft,
        Published
    }
    

Now that our enum is created, we need to add the new property to our entity that is of the enum Status.

  1. Open up our Blog entity and add a new property

    [Required]
    [MaxLength(25)]
    public Status Status { get; set; }
    

Now we need to tell EF Core how to handle the enum.

  1. Open up our BlogMap.cs and add the following to the Configure to set the default value and convert it to a string

    entity.Property(t => t.Status)
        .HasDefaultValue(SyncStatus.Draft)
        .HasConversion<string>();
    
  2. Also, need to add the using for EF Core to the BlogMap.cs

    using Microsoft.EntityFrameworkCore;
    

The last thing we need to do is create our migration script to add the new column.

  1. Run the following command to generate the migration script

    dotnet ef migrations add AddStatusField -o .\EntityFramework\Migrations\
    
  2. Then we need to run the script against our database.

    dotnet ef database update
    

Now our application will only allow the enum values to be entered through EF Core for our Status column.

See Code for Post