Reputation: 34309
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
Upvotes: 6
Views: 5091
Reputation: 31620
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:
Upvotes: 7
Reputation: 205849
Looks like the problem is with the enum
underlying type.
I didnt' find any information, but a quick test shows that the following types are supported
byte, short, int, long
and the following are not
sbyte, ushort, uint, ulong
Upvotes: 5