Using enum as FK on EF 6
-
23-12-2019 - |
Question
I'd like to use an enum as Foreign Key in a Code-First app. Since enums are stored as int, I thought I could use the attribute [ForeignKey] on the enum property, but it throws this exception:
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
Here is an example of what I am trying to do:
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; }
...
}
Is it possible to do this or something similar through fluent api or migrations?
Thanks
Solution
Here's one I made earlier: https://www.nuget.org/packages/ef-enum-to-lookup
It's a nuget package that provides a method you can call in your Seed
(initializer and/or migrations) which will automatically build lookup tables and add FKs where the enum is used. Usage info.
Enjoy :-) And let me know if it works for you (or anyone else for that matter!)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow