[英]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. 我来自Java,现在正在使用C#和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
. 我有一个Company
有哪几种属性列表到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
. 当我使用EF将其转换为数据库时,我为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 我希望Person的数据库方案是
|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. 所有这些Company_ID *列均具有对同一Company表的引用,因此,我相信并非只有一个列可用于此引用,然后松开所有这些null
引用是不可能的。
I need a solution with Fluent API, not Data Annotation. 我需要使用Fluent API(而不是数据注释)的解决方案。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.