Search code examples
c#sql-serverentity-frameworkef-code-firstcode-first

Entity Framework complex relationship


I have class A which inherits from class B, at the same time class A has many instances of B. Class B contains class A property as a reference.

I'm looking for the best way to map this relationship using EF Codefirst.


Solution

  • A is NOT inherited from B. They have a few common properties like this:

    class ABCommon
    {
        //common properties here
    }
    
    class B : ABCommon
    {
        public virtual A A { get; set; }
        //this property makes everything crazy if A inherits from B
    }
    
    public A : ABCommon
    {
        public virtual ICollection<B> Bs { get; set; }
    }
    

    It's just a simple 1-to-many relationship between A and B.