2

我想在 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 或迁移来执行此操作或类似的操作?

谢谢

4

1 回答 1

1

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

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

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

于 2014-09-28T04:54:01.613 回答