gpt4 book ai didi

entity-framework - EF Core 2.0枚举存储为字符串

转载 作者:行者123 更新时间:2023-12-04 07:09:00 25 4
gpt4 key购买 nike

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

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

但是当需要查询EF时,它不知道将字符串解析为枚举。我该如何查询:
context
.Company
.Where(x => x.Stage == stage)

唯一的异常(exception):将varchar值“机会”转换为数据类型int时转换失败

最佳答案

值(value)转换功能是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
}

您可以使用自己的转换
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);

关于entity-framework - EF Core 2.0枚举存储为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47721246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com