如何使EF Core数据库首先使用枚举? [英] How can I make EF Core database first use Enums?
问题描述
我正在使用EF Core和数据库优先方法,并使用 Scaffold-DbContext命令生成我的DbContext /实体。
I'm using EF Core with database-first approach using the "Scaffold-DbContext"-command to generate my DbContext / Entities.
我如何指导脚手架-DbContext某个表中的某个字段应该生成使用枚举而不是一个整数的代码吗?
How can I instruct Scaffold-DbContext that a certain field in a certain table should generate code to use an Enum instead of just an int?
这是您在常规EF中常用的方法:
https://www.devu.com/cs-asp/lesson-69-mapping-enum-types-entity-properties-framework-designer/
This is how you used to do it in regular EF: https://www.devu.com/cs-asp/lesson-69-mapping-enum-types-entity-properties-framework-designer/
该枚举已在代码中定义:
This enum is already defined in code:
public enum StateEnum {
Ok = 1,
Fail = 2
}
这是Scaffold-DbContext给我的
This is what Scaffold-DbContext gives me
public partial class Foo
{
public int Id { get; set; }
public int State { get; set; }
}
这就是我要创建的内容:
This is what I want it to create:
public partial class Foo
{
public int Id { get; set; }
public StateEnum State { get; set; }
}
推荐答案
从实体框架核心开始 2.1 ,EF支持值转换专门解决需要将属性映射到其他类型以进行存储的情况。
Starting with Entity Framework Core 2.1, EF supports Value Conversions to specifically address scenarios where a property needs to be mapped to a different type for storage.
专门用于枚举,可以使用提供的 EnumToStringConverter
或 EnumToNumberConverter
。
Specifically for Enums, you can use the provided EnumToStringConverter
or EnumToNumberConverter
.
这篇关于如何使EF Core数据库首先使用枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!