如何让 EF Core 数据库首先使用 Enums?

编程入门 行业动态 更新时间:2024-10-26 23:28:57
本文介绍了如何让 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 中的做法:www.devu/cs-asp/lesson-69-mapping-enum-types-entity-properties-framework-designer/

This is how you used to do it in regular EF: www.devu/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.

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

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

更多推荐

如何让 EF Core 数据库首先使用 Enums?

本文发布于:2023-11-14 10:38:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586989.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库   EF   Core   Enums

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!