I have the following model:
public class Order
{
public int Id { get; set; }
public ItemType ItemType { get; set; }
public int ItemId { get; set; }
}
public enum ItemType
{
Customer, Organization, Department, //etc
}
The ItemId is a foreignkey to a separate model/table. The above model maps as-is with the underlying table.
Now I would like to automatically load the related entities when loading an Order.
Is this possible by using composite foreign keys when mapping, as in:
public class Order
{
public int Id { get; set; }
public ItemType ItemType { get; set; }
public int ItemId { get; set; }
public ItemTypeCustomer => ItemType.Customer;
public ItemTypeOrganization => ItemType.Organization;
public ItemTypeDeparment => ItemType.Department;
public Customer Customer { get; set; }
public Organization Organization { get; set; }
public Department Department { get; set; }
}
modelBuilder.Entity<Order>()
.HasOptional(p => p.Customer)
.WithMany()
.HasForeignKey(p => new { p.ItemTypeCustomer , p.ItemId });
Would the above work? Is it even possible to build something like this using code-first?