Search code examples
c#databaseentity-frameworkvisual-studio-2012fluent-interface

How to map complex one-to-many with Entity Framework and Fluent API


I'm coming from Java and is now implementing an existing system into a database with C# and Entity Framework.

Since I cannot show the actual classes here, I've tried to make an example identical to my problem, which is as follows. I have a Company which has several property lists to Person. When I'm using EF to convert this into the database, I'm getting a new foreign key column for each instance of Person.

Company
   public GUID CompanyID {get,set}
   public List<Person> Employee{get,set}
   public List<Person> Janitors {get,set}
   public List<Person> Students {get,set}
   public List<Person> Professors {get,set}    

Person
   public GUID CompanyID {get,set}

I would like the database scheme of Person to be

|Column 1 | Column 2 | Column 3 | Company_FK |
----------------------------------------------

But now it is more like this

| Column 1 | Column 2 | Column 3 | Company_ID  | Company_ID1 | Company_ID2 ...
--------------------------------------------------------------------------
                                     null          reference      null
                                     null          reference      null
                                    reference         null        null
               ~~~~~~~~~~~~~~~~~~~~~~etc~~~~~~~~~~~~~~~~~~

All those Company_ID* columns have references to the same Company table, therefor I believe that it is not impossible to just have one column for this reference, and then loose all those null references.

I need a solution with Fluent API, not Data Annotation.


Solution

  • Try this with your company configuration:

    HasMany(x => x.Employee).WithRequired().HasForeignKey(x => x.CompanyID);
    HasMany(x => x.Janitors).WithRequired().HasForeignKey(x => x.CompanyID);
    HasMany(x => x.Students).WithRequired().HasForeignKey(x => x.CompanyID);
    HasMany(x => x.Professors).WithRequired().HasForeignKey(x => x.CompanyID);