EF Core 2.0 Enums stored as string

前端 未结 3 1051
说谎
说谎 2020-12-16 11:51

I was able to store an enum as a string in the database.

builder.Entity(eb =>
{
    eb.Property(b => b.Stage).HasColumnType(\"varchar(20         


        
3条回答
  •  执念已碎
    2020-12-16 12:36

    Value Conversions feature is new in EF Core 2.1.

    Value converters allow property values to be converted when reading from or writing to the database. This conversion can be from one value to another of the same type (for example, encrypting strings) or from a value of one type to a value of another type (for example, converting enum values to and from strings in the database.)

    public class Rider
    {
        public int Id { get; set; }
        public EquineBeast Mount { get; set; }
    }
    
    public enum EquineBeast
    {
        Donkey,
        Mule,
        Horse,
        Unicorn
    }
    

    You can use own conversion

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity()
            .Property(e => e.Mount)
            .HasConversion(
                v => v.ToString(),
                v => (EquineBeast)Enum.Parse(typeof(EquineBeast), v));
    }
    

    or Built-in converter

    var converter = new EnumToStringConverter();
    
    modelBuilder
        .Entity()
        .Property(e => e.Mount)
        .HasConversion(converter);
    

提交回复
热议问题