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

前端 未结 8 1582
失恋的感觉
失恋的感觉 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:50

    Excellent @AlbertoMonterio! To get this to work with ASP.NET CORE / EF Core I made a few adjustments to Alberto's solution.

    For brevity, only the modifications are shown below:

    Create a extension method to get description from enum and seed values

    using System;
    using System.ComponentModel;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using Microsoft.EntityFrameworkCore; //added
    using Microsoft.EntityFrameworkCore.Metadata.Builders; //added
    
    public static class Extensions
    {
        //unchanged from alberto answer
        public static string GetEnumDescription(this TEnum item)
            => item.GetType()
                   .GetField(item.ToString())
                   .GetCustomAttributes(typeof(DescriptionAttribute), false)
                   .Cast()
                   .FirstOrDefault()?.Description ?? string.Empty;
    
        //changed
        public static void SeedEnumValues(this ModelBuilder mb, Func converter)
        where T : class => Enum.GetValues(typeof(TEnum))
                               .Cast()
                               .Select(value => converter((TEnum)value))
                               .ToList()
                                .ForEach(instance => mb.Entity().HasData(instance));
    }
    
    
    

    Add the seed in Configuration.cs

    Add Seeding to OnModelCreating of DataContext

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.SeedEnumValues(e => e);
    }
    

    提交回复
    热议问题