Search code examples
asp.net.netentity-frameworkedmxedmx-designer

Entity Framework swaps navigational properties


I am using EF with DB first approach. I am facing an issue while updating the EDMX file. Suppose I have a table InvoiceT and another table LookupT. Now, in InvoiceT I have a column InvoiceType having FK relation with LookupT. Now entity creates a navigational property in InvoiceT class with the name LookupT. So far, its good.

Now I added another column with name InvoiceStatus and FK with LookupT. Now entity creates another navigational property with the name LookupT1. But the issue here is that first navigational property LookupT is not pointing to its original data i.e. InvoiceType. Instead, its pointing to InvoiceStatus data now. Can anybody please explain to me why its behaving like this and what can I do about it?

public class InvoiceT
{
    public int InvoiceId {get;set;}
    public int InvoiceStatusLkpId {get;set;}
    public int InvoiceTypeLkpId {get;set;}
    public virtual LookupT LookupT {get;set;}    // Previously pointing to Type. Now to Status.
    public virtual LookupT LookupT1 {get;set;}    // Pointing to Type

}

public class LookupT
{
    public int LookupId {get;set;}
    public string LookupValue {get;set}
    public virtual ICollection<InvoiceT> InvoiceT {get;set;}
    public virtual ICollection<InvoiceT> InvoiceT1 {get;set;}
}

Solution

  • So I figured out the issue. Seems like when EF creates the navigational properties, it does this in order of FK relation names i.e. if I have two FK relations with name RelationA and RelationB, then the navigational property for RelationA will be created first and then for RelationB. In my scenario, the relation names for my type and status were 'FK_InvoiceT_LookupT_InvoiceTypeLkpId' and 'FK_InvoiceT_LookupT_InvoiceStatusLkpId' (which SQL designer generates automatically) respectively and EF first generated the navigational property for the relation that was added later and it messed up my ordering. So all I had to do was to update relation names in order in which they were added and everything started working fine.