I have built a lookup table based on enums, pretty much based on that suggestion: How to create a table corresponding to enum in EF6 Code First?
Now my problem is that I am unable to configure the foreign key for MyEntity.OrderType to the OrderType table.
For more context, these are my types:
public enum OrderTypeEnum
{
Buy = 1, Sell = 2
}
public class OrderType : EntityEnumAdapterBase<OrderTypeEnum>
{
// this base class implements Id, Name and Description properties as can be seen here:
// https://stackoverflow.com/questions/34557574/how-to-create-a-table-corresponding-to-enum-in-ef6-code-first/34558339#34558339
}
public partial class MyEntity
{
[Required]
public OrderType Type { get; set; } // stored as int using a value conversion
}
Now as the database schema for MyEntity is generated, it's lacking the foreign key constraint on MyEntity.Type
to the OrdeType.Id
.
How can I achieve that?
What I have tried so far, was adding a navigaion property on MyEntity as such:
public class OrderType : EntityEnumAdapterBase<OrderTypeEnum>
{
public IList<MyEntity> MyEntities { get; set; }
}
Then configure it as such in OnModelCreating(ModelBuilder modelBuilder)
modelBuilder.Entity<MyEntity>()
.HasOne(bc => bc.Type)``
.WithMany(c => c.MyEntities)
.HasForeignKey(bc => bc.TypeId);
This fails with messsage: 'Type' cannot be used as a property on entity type 'MyEntity' because it is configured as a navigation.
So, how do I tackle adding FK constraints to tables generated from enums? The mentioned approach also seems a bit verbose, as I had to add MyEntity.TypeId
(of type int) and OrderType.MyEntities.
Ideally on MyEntity
I even wouldn't want to have OrderType
, but rather OrderTypeEnum
instead as such:
public partial class MyEntity
{
[Required]
public OrderTypeEnum Type { get; set; } // stored as int using a value conversion
}