Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an enum as a primary key with EF

Is it possible to use an enum as a primary key for a table? I have something like the following:

public enum SpecialId : uint {}

public class Thing 
{
     public SpecialId Id { get; set; }
}

public class MyContext : DbContext
{
     public DbSet<Thing> Things { get; set; }
}

But i get the following error on initialisation:

An unhanded exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll

Additional information: The key component 'Id' is not a declared property on type 'Thing'. Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.

This does say it needs to be a primitive (an enum is only castable to primitave) but the EF post around enums sugguests this is possible

Enums as keys

In addition, properties of enum types can participate in the definition of primary keys, unique constraints and foreign keys, as well as take part in concurrency control checks, and have declared default values.

Am I doing something wrong or is this simply not supported?

On a side not I know that I could hack in this functionality using another property with not mapped on it to translate keys to enums. This is not the answer I am looking

like image 608
Not loved Avatar asked Dec 24 '22 09:12

Not loved


1 Answers

This does not work because your enum is based on uint. EF does not support unsigned integral types in general (i.e. you could use the uint type for a property) and therefore it won't work for enum properties as well.

I am personally not a big fan of enum keys. Here is just a couple of reasons:

  • the values in the database can get out of sync very easily with your enum definition
  • this can be broken out of box if the database generates the keys - typically database starts generating IDs from 1 but the first enum member is 0
  • enum types typically have just a few constants/members. While it is possible to have values that are in the range of the enum underlying type but don't have a corresponding constant in the enum type (and EF supports this) this defeats the purpose of using the enum type
like image 141
Pawel Avatar answered Jan 12 '23 03:01

Pawel