过去几年我一直在使用 Linq2Sql 并习惯了一些功能,比如在数据库中有一个 int
或 tinyint
字段,我重新定义了这些功能在 DBML 文件中为枚举类型,因此与枚举相比,直接运行 SQL 查询非常方便(请参阅 here 了解我 3 年前关于该主题的问题,以及那里的 answer)。
现在我正在开始一个使用 Entity Framework 5 的项目,虽然 EF 似乎已经做对了很多 L2S 做不到的事情(例如分离/重新附加),但我很沮丧地发现似乎没有是将此类字段的 C# 类型更改为枚举的任何简单方法。
有没有人找到一种方法来干净地做到这一点,以便我可以有这样的查询:
var q = entities.Things.Where(t => t.Status == TStatus.Closed);
(不,我不想强制转换为 int
或 byte
内联)。
最佳答案
代码优先
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/