【问题标题】:Using enum as FK on EF 6在 EF 6 上使用枚举作为 FK
【发布时间】: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.TypeMasterType.MasterTypeId 有不同的类型。
  • 另外......为什么不在你的枚举上使用DescriptionAttribute
  • Aron,我需要存储比描述更多的信息,这就是我使用另一个表的原因。问题是 MasterType 也存储了其他枚举的信息,所以我可以在 PK 中使用枚举类型
  • hvd,我知道,但是在数据库中枚举存储为 int,所以我认为这可能是一种方法。

标签: entity-framework enums ef-code-first entity-framework-6.1


【解决方案1】:

这是我之前做的一个:https://www.nuget.org/packages/ef-enum-to-lookup

这是一个 nuget 包,它提供了一种可以在 Seed(初始化程序和/或迁移)中调用的方法,该方法将自动构建查找表并在使用枚举的地方添加 FK。 Usage info.

享受 :-) 如果它对您有用(或其他任何人!)

,请告诉我

【讨论】:

  • 不错!我会尽快尝试,因为我最近做的 ADO.NET 比 EF 多。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
相关资源
最近更新 更多