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

查看:64
本文介绍了如何使EF Core数据库首先使用枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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屋!

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