EF Core 2.0枚举存储为字符串 [英] EF Core 2.0 Enums stored as string

查看:378
本文介绍了EF Core 2.0枚举存储为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够将枚举作为字符串存储在数据库中。

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)");
});

但是当需要查询EF时,它不知道将字符串解析为枚举。我该如何查询:

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)

这是例外:转换varchar值'Opportunity'时转换失败数据类型为int

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

推荐答案

值转换功能是EF Core 2.1中的新增功能。

Value Conversions feature is new in EF Core 2.1.


当从数据库中读取或写入
时,值转换器允许转换属性值。此转换可以是从一个值
到另一个相同类型的值(例如,加密字符串),也可以是从一种类型的
a值到另一个类型的值(例如,
转换枚举)

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
}

您可以使用自己的转换

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

或内置转换器

var converter = new EnumToStringConverter<EquineBeast>();

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

这篇关于EF Core 2.0枚举存储为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆