Search code examples
entity-frameworkef-code-firstnavigation-properties

EF6 Navigation Properties Same Type To Single Inverse


Im not sure if this is possible. Suppose I have this:

public class Thing{
    public int ThingId {get; set;}
    public virtual Item ItemA {get; set;}
    public virtual Item ItemB {get; set;}
}

public class Item{
    public int ItemId {get; set;}
}

How can I make a single navigation property on Item that brings me either to ItemA or ItemB? Or something where I can use item.Thing!=null? item.Thing.ItemA or item.Thing.ItemB?

I've tried a bunch of things but can't get it to work.


Solution

  • In the Thing class there are two items, which implies that a single Item can be part of one or more Things. (Ex: the same item could be ItemA for Thing1 and it could be ItemB for Thing2). In this case it is not possible to have a FK column in the Item table because it has a one-to-many relationship with Thing.

    The best you could do is have the Item class have a list of Things that it belongs to. You can also determine which Things it is ItemA for and which Things it is ItemB for.

    class Thing
    {
        public int ThingId { get; set; }
    
        [InverseProperty("ItemAFor")]
        public Item ItemA { get; set; }
    
        [InverseProperty("ItemBFor")]
        public Item ItemB { get; set; }
    }
    
    class Item
    {
        public int ItemId { get; set; }
    
        // Things where this Item is ItemA
        public List<Thing> ItemAFor { get; set; }
    
        // Things where this Item is ItemB
        public List<Thing> ItemBFor { get; set; }
    }