EF Core 2.0 Enums stored as string

ⅰ亾dé卋堺 提交于 2019-11-30 03:16:53

问题


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

builder.Entity<Company>(eb =>
{
    eb.Property(b => b.Stage).HasColumnType("varchar(20)");
});

But when it comes time to query EF doesn't know to parse the string into an enum. How can I query like so:

context
    .Company
        .Where(x => x.Stage == stage)

This is the exception: Conversion failed when converting the varchar value 'Opportunity' to data type int


回答1:


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<Rider>()
        .Property(e => e.Mount)
        .HasConversion(
            v => v.ToString(),
            v => (EquineBeast)Enum.Parse(typeof(EquineBeast), v));
}

or Built-in converter

var converter = new EnumToStringConverter<EquineBeast>();

modelBuilder
    .Entity<Rider>()
    .Property(e => e.Mount)
    .HasConversion(converter);



回答2:


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



来源:https://stackoverflow.com/questions/47721246/ef-core-2-0-enums-stored-as-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!