如何在实体框架中使用 Fluent API 映射一对多关系中的枚举?

Isa*_*pis 5 c# enums entity-framework

我的问题很简单,并且与另一个问题相关(How to map an enum in a one-to-many relationship with NHibernate?),尽管在这里我特别询问实体框架的流畅 API。

假设(同一示例)我的模型中有这两个实体,一个引用类型(用户),另一个枚举(角色)。

class User { int id; IList<Roles> Roles; }

enum Roles { Worker, Manager, Director }
Run Code Online (Sandbox Code Playgroud)

或者为了清楚起见,在这个表示中......

[users]   [ roles ] 
+-----+   +-------+
| id  |   |user_id|
+-----+   +-------+
          | value | <- [Represented by the enum]
          +-------+
Run Code Online (Sandbox Code Playgroud)

现在我想使用 Fluent API 将其映射到实体框架中的数据库,但如果我尝试...

 HasMany(x => x.Roles)
   .Cascade.All()
   .Table("UserRoles")
   .Element("RolesEnum");
Run Code Online (Sandbox Code Playgroud)

...它将失败,因为HasMany()不是引用类型。

有没有一种方法可以在流畅的 API 中做到这一点,而不涉及将我的业务模型从枚举更改为类?

Ton*_*ony 1

这并不能直接回答您的问题,但您是否考虑过将 Role 枚举制作为标志枚举并将其作为整数存储在 User 表中?

你可以这样做:

class User 
{ 
    public int Id { get; set; } 
    public UserRole Roles { get; set; } 
}

[Flags]
public enum UserRole
{
    Guest = 0,
    Worker = 1,
    Manager = 1 << 2,
    Director = 1 << 3,
}
Run Code Online (Sandbox Code Playgroud)

然后,要在用户表中存储多个角色,您可以像这样分配它们:

_user.Roles = UserRole.Worker | UserRole.Manager
Run Code Online (Sandbox Code Playgroud)