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

前端 未结 8 1594
失恋的感觉
失恋的感觉 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 18:07

    I might be a bit late for the party but I didn't find the answer I was looking for here.

    While looking around in the EntityFramework documentation I found the solution, it is the first example in Value Conversions

    With this you can make a nice extension method if you want. i.e.

    public static void HasEnum(this EntityTypeBuilder entityBuilder, Expression> propertyExpression)
            where TEntity : class
            where TProperty : Enum
        {
            entityBuilder.Property(propertyExpression)
                .HasConversion(
                    v => v.ToString(),
                    v => (TProperty)Enum.Parse(typeof(TProperty), v)
                );
        }
    

    Then use it in your OnModelCreating:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity()
            .HasEnum(e => e.YourProperty);
    }
    

提交回复
热议问题