Why is Entity Framework resetting my enum to default value when saved
12:56 06 Jan 2021

I am debugging the following baffling behaviour. I have an entity ExampleEntity which contains a [Required] enum, which for migration reasons, has a default value. When inserting a new ExampleEntity, I am specifying the value this field should take. Inspecting in the debugger reveals the value has been set correctly in the local version of the DbSet. However, whenever I call SaveChanges() on the context, the enums value is reset to the configured default value.

The models:

public enum ExampleEnum
{
    Mecury,
    Venus,
    Earth,
    Mars
}

internal class ExampleEntity
{
    public int id { get; set; }

    [Required]
    public ExampleEnum Val { get; set; }
}

internal class EFContext : DbContext
{
    public EFContext(DbContextOptions options) : base(options)
    {
    }

    public virtual DbSet Ents { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
       modelBuilder.Entity(entity =>
       {
            entity.Property(e => e.Val).HasDefaultValue(ExampleEnum.Earth);
       });
    }
}

The test code:

class Program
{
    private static DbConnection CreateInMemoryDatabase()
    {
        var connection = new SqliteConnection("Filename=:memory:");
        connection.Open();
        return connection;
    }

    static void Main(string[] args)
    {
        var ContextOptions = new DbContextOptionsBuilder()
                .UseSqlite(CreateInMemoryDatabase())
                .Options;

        using (var context = new EFContext(ContextOptions))
        {
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();
        }

        using (var db = new EFContext(ContextOptions))
        {
            var newEntity = new ExampleEntity
            {
               Val = ExampleEnum.Mecury,
            };
            db.Ents.Add(newEntity);
            db.SaveChanges();
        }

        using (var db = new EFContext(ContextOptions))
        {
            var savedEnt = db.Ents.First();
            Console.WriteLine(savedEnt.Val.ToString());
        }
    }
}

I expected the value printed to be Mercury but it prints out the configured default Earth. I can resolve this by after saving the changes, setting the Val to be the desired value:

var newEntity = new ExampleEntity
{
   Val = ExampleEnum.Mecury,
};
db.Ents.Add(newEntity);
db.SaveChanges();
newEnttity.Val = ExampleEnum.Mecury;
db.SaveChanges()
c# entity-framework entity-framework-core