c# - 在 Entity Framework 中将 tinyint 字段表示为枚举

标签 c# linq entity-framework entity-framework-5

过去几年我一直在使用 Linq2Sql 并习惯了一些功能,比如在数据库中有一个 inttinyint 字段,我重新定义了这些功能在 DBML 文件中为枚举类型,因此与枚举相比,直接运行 SQL 查询非常方便(请参阅 here 了解我 3 年前关于该主题的问题,以及那里的 answer)。

现在我正在开始一个使用 Entity Framework 5 的项目,虽然 EF 似乎已经做对了很多 L2S 做不到的事情(例如分离/重新附加),但我很沮丧地发现似乎没有是将此类字段的 C# 类型更改为枚举的任何简单方法。

有没有人找到一种方法来干净地做到这一点,以便我可以有这样的查询:

var q = entities.Things.Where(t => t.Status == TStatus.Closed);

(不,我不想强​​制转换为 intbyte 内联)。

最佳答案

代码优先

EF5 Code First 支持 .NET 4.5 上的枚举属性。以下实体将在数据库中创建一个 int 字段:

public class Event
{
    public int EventId { get; set; }
    public Status Status { get; set; }
}

public enum Status
{
    Open,
    Closed,
    Pending
}

您可以查询的内容:

db.Events.Where(e => e.Status == Status.Pending)

数据库优先

this post 中所述,下面是您如何为 Database First 完成同样的事情。

Go to the model browser and create a new enum type, then go to whatever column you wish to use it on and change its type to the enum that you just created.

关于c# - 在 Entity Framework 中将 tinyint 字段表示为枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12371445/

相关文章:

c# - 如果我使用 TypeBuilder 构建具有属性的类型,我是否需要使用 propertyBuilder?

c# - 从 Int 表达式创建 bool Linq to SQL 表达式

c# - 从包含逗号分隔值的字符串数组中查找项目的索引

c# - SQL Server 到 Entity Framework 数据类型的映射

c# - LINQ to Entities 无法识别方法 'Int32 Parse(System.String)' 方法,

c# - 为什么我必须指定所有泛型类型参数?

c# - 如何将1个字符串分成多个字符串

c# - Linq 查询在编译时不起作用

c# - 当前上下文中不存在名称 'insert name here'

c# - Blazor:在此之前的操作完成之前,在此上下文中开始了第二次操作