2

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

  • Shirley you want `public UserType MasterTypeId { get; set; }` – Aron Apr 14 '14 at 09:47
  • Right, what Aron said. The error message is telling you that `User.Type` and `MasterType.MasterTypeId` have different types. –  Apr 14 '14 at 09:47
  • Also...why not just use `DescriptionAttribute` on your enum? – Aron Apr 14 '14 at 09:49
  • Aron, I need to store more info than the description, thats why I use another table. The problem is that MasterType stores information about other enums too, so I can use the enum type in the PK – Adrián López Apr 14 '14 at 09:59
  • hvd, I know that, but in the database the enum is stored as an int, so I thought that it may be a way to do this. – Adrián López Apr 14 '14 at 10:02
  • I could add another property to store the Id and add the [NotMapped] attribute to the enum type. Then I can add the assignments of the Id in the getter and setter of the enum property, but doing it this way ends up with one extra property for each enum... – Adrián López Apr 14 '14 at 10:04
  • similar to http://stackoverflow.com/questions/11167665/ef5-code-first-enums-and-lookup-tables – Tim Abell Jun 01 '16 at 15:13

1 Answers1

1

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!)

Tim Abell
  • 11,186
  • 8
  • 79
  • 110