【发布时间】:2014-04-14 09:44:14
【问题描述】:
我想在 Code-First 应用程序中使用枚举作为外键。由于枚举存储为 int,我认为我可以在枚举属性上使用属性 [ForeignKey],但它会引发此异常:
The types of all properties in the Dependent Role of a referential constraint
must be the same as the corresponding property types in the Principal Role
这是我正在尝试做的一个示例:
public enum UserType
{
Administrator = 1,
Member = 2
}
public class User
{
public int UserId { get; set; }
public string Login { get; set; }
[ForeignKey("TypeDetails")]
public UserType Type { get; set;}
public virtual MasterType TypeDetails { get; set; }
}
public class MasterType
{
public int MasterTypeId { get; set; }
public string Description { get; set; }
...
}
是否可以通过 fluent api 或迁移来执行此操作或类似的操作?
谢谢
【问题讨论】:
-
雪莉你要
public UserType MasterTypeId { get; set; } -
对,阿伦说的。错误信息告诉你
User.Type和MasterType.MasterTypeId有不同的类型。 -
另外......为什么不在你的枚举上使用
DescriptionAttribute? -
Aron,我需要存储比描述更多的信息,这就是我使用另一个表的原因。问题是 MasterType 也存储了其他枚举的信息,所以我可以在 PK 中使用枚举类型
-
hvd,我知道,但是在数据库中枚举存储为 int,所以我认为这可能是一种方法。
标签: entity-framework enums ef-code-first entity-framework-6.1