How can I make EF Core database first use Enums?

后端 未结 7 893
灰色年华
灰色年华 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:53

    This is the same question answered at: Does EF7 support enums?

    0 讨论(0)
  • 2020-12-06 04:54

    Doesn't value conversion in EF Core 2.1 do what you need now?

    https://docs.microsoft.com/en-us/ef/core/modeling/value-conversions

    Quick Example:

      entity.Property(e => e.MyEnumField)
                .HasMaxLength(50)
                .HasConversion(
                    v => v.ToString(),
                    v => (MyEnum)Enum.Parse(typeof(MyEnum),v))
                    .IsUnicode(false);
    
    0 讨论(0)
  • 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<Foo>().Property(x => x.State).HasDefaultValue(StateEnum.Ok);
        }
    }
    
    0 讨论(0)
  • 2020-12-06 04:54

    Currently, EF core does not support enums. Code like this:

    public class MyDbContext : DbContext
    {      
        protected override void OnModelCreating(ModelBuilder builder) 
        {
            builder.Entity<StateEnum>(e => {...});
        }
    }
    

    does not compile with the message:

    CS0452 C# The type must be a reference type in order to use it as parameter 'TEntity' in the generic type or method

    Solution: you can use enumeration classes instead

    0 讨论(0)
  • 2020-12-06 04:55

    You can have you enum (U) and an entity (T) representing enum values in the database

    public static T[] BuildEntityObjectsFromEnum<T, U>() where U: Enum where T : new()
        {
            var listObjectsToReturn = new List<T>();
            Dictionary<string, int> dictionary = Enum.GetValues(typeof(U)).Cast<U>().ToDictionary(t => t.ToString(), t =>  Convert.ToInt32(t));
    
            foreach (var item in dictionary)
            {
                var newObject = new T();
                Type classType = typeof(T);
                classType.GetProperties()[0].SetValue(newObject, item.Value); // Enum int id
                classType.GetProperties()[1].SetValue(newObject, item.Key); // Enum string value
                listObjectsToReturn.Add(newObject);
            }
            return listObjectsToReturn.ToArray();
        }
    

    Then you can seed the table from the enum

    modelBuilder.Entity<T>().HasData(BuildEntityObjectsFromEnum<T,U>());
    
    0 讨论(0)
  • 2020-12-06 05:12

    Try this solution:

    public enum StateEnum {
          Ok = 1,
          Fail = 2
    }
    
    public partial class Foo
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public StateEnum State
        {
            get => (StateEnum)StateId;
            set => StateId = (int)value;
        }
    }
    
    0 讨论(0)
提交回复
热议问题