How can I make EF Core database first use Enums?

后端 未结 7 1009
灰色年华
灰色年华 2020-12-06 04:43

I\'m using EF Core with database-first approach using the \"Scaffold-DbContext\"-command to generate my DbContext / Entities.

How can I instruct Scaffold-DbContext t

7条回答
  •  天涯浪人
    2020-12-06 04:54

    I got here because of the question title. Not sure if this works in the "Scaffold-DbContext" but it does in DbContext (Microsoft.EntityFrameworkCore 2.0.1.0) by setting the base type of the enum explicitly even if the default underlying type of enumeration elements is int. You can use Fluent API to set default values with it too (especially this case where the enum starts with 1).

    public enum StateEnum : int
    {
        Ok = 1,
        Fail = 2
    }
    

    The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.

    So I think this would work for any of these. enum (C# Reference)

    public class MyDbContext : DbContext
    {      
        protected override void OnModelCreating(ModelBuilder builder) 
        {
            builder.Entity().Property(x => x.State).HasDefaultValue(StateEnum.Ok);
        }
    }
    

提交回复
热议问题