如何让 EF Core 数据库首先使用 Enums? [英] How can I make EF Core database first use Enums?

查看:16
本文介绍了如何让 EF Core 数据库首先使用 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.

如何指示 Scaffold-DbContext 某个 中的某个 字段 应该生成代码以使用 Enum 而不仅仅是一个 int?

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

推荐答案

从 Entity Framework Core 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.

特别是对于枚举,您可以使用提供的 EnumToStringConverterEnumToNumberConverter.

Specifically for Enums, you can use the provided EnumToStringConverter or EnumToNumberConverter.

这篇关于如何让 EF Core 数据库首先使用 Enums?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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