I am working on a small architecture change to an existing application using Entity Framework and trying to get a base class to have a navigation property, but for some reason EF keeps trying to add it twice and I'm not entirely sure why.
The class structure is setup as:
public abstract class PurchaseOrderItem
{
//foreign key reference
public long PurchaseOrderId { get; set; }
//parent entity
public virtual PurchaseOrder PurchaseOrder { get; set; }
}
public class PurchaseOrderProduct : PurchaseOrderItem
{
//general properties that a PurchaseOrderItem doesn't have
}
public class PurchaseOrder
{
//navigation property to items, which will include purchase order products
public virtual ICollection<PurchaseOrderItem> Items { get; set; }
}
The navigation property on PurchaseOrderItem is setup as:
HasRequired(p => p.PurchaseOrder).WithMany(p => p.Items).HasForeignKey(p => p.PurchaseOrderId);
The database structure is a one-to-one relationship, as is the actual configuration setup inside PurchaseOrderProduct. When the SQL query is run by Entity Framework, it includes the default PurchaseOrderId key as expected on the PurchaseOrderItem, but then it also includes PurchaseOrder_Id targeting the PurchaseOrderProduct table, which fails because it doesn't exist since that's associated with the base class and intentionally not on the inherited classes.
Has anyone else run into this before and/or have any suggestions? It seems pretty straightforward.
** UPDATE **
I started playing with this further, by creating new classes that mimic this structure called TestPOItem and TestPOItemProduct, but that lead to another issue where it was saying TestPOItem and PurchaseOrderItem could not be configured to map to PurchaseOrderItems (a table that doesn't exist and isn't configured anyway) which further lent itself to EF doing something very strange.
Even stranger, when I added PurchaseOrderProduct_Id as a property on the POCO PurchaseOrderProduct entity and marked it as Ignore(p => p.PurchaseOrderProduct_Id), it still added it and where it got incredibly weird is when I added the foreign key references from PurchaseOrderItem to PurchaseOrderProduct and removed them from PurchaseOrderItem, I re-ran the unit test and it was suddenly looking for PurchaseOrder_Id2 which definitely exists nowhere.
Unfortunately, I think I have to chalk this up to EF getting itself tripped up somewhere internally and come up with an alternate solution. We use plenty of one-to-one relationships in this system, but never have any of the abstract base classes had a navigation property on them. It's always the inherited class that has those specified.