How to create a table corresponding to enum in EF6 Code First?

前端 未结 8 1595
失恋的感觉
失恋的感觉 2020-11-29 17:10

I\'ve followed MSDN on how to handle enumerations in Code First for EF6. It worked, as supposed to but the field in the created table that refers to the enu

8条回答
  •  余生分开走
    2020-11-29 17:56

    Another approach that works (and feels simpler to me) in EF Core:

    Your Enum

    public enum Color
    {
        Red = 1,
        Blue = 2,
        Green = 3,
    }
    

    Db Tables

    public class CustomObjectDto
    {
        public int ID { get; set; }
    
        // ... other props
    
        public Color ColorID { get; set; }
        public ColorDto ColorDto { get; set; }
    }
    
    public class ColorDto
    {
        public Color ID { get; set; }
        public string Name { get; set; }
    }
    

    Your DbContext

    public class Db : DbContext
    {
        public Db(DbContextOptions options) : base(options) { }
    
        public DbSet CustomObjects { get; set; }
        public DbSet Colors { get; set; }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // Seed database with all Colors
            foreach (Color color in Enum.GetValues(typeof(Color)).Cast())
            {
                ColorDto colorDto = new ColorDto
                {
                    ID = color,
                    Name = color.ToString(),
                };
    
                modelBuilder.Entity().HasData(colorDto);
            }
        }
    }
    

    In code I basically only use the enum Color (never ColorDto). But it's still nice to have the 'Colors' table with an FK in the 'CustomObjects' table for sql queries and views.

提交回复
热议问题