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
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With