将具有不同主键的两个表映射到一个实体

时间:2013-03-25 17:59:10

标签: c# entity-framework

我正在使用遗留数据库上的EF创建应用程序。在数据库中有两个我关注的表。结构(以C#形式)如下所示:

public class Employee
{
    public int employeeID {get; set;} //primary key
    public string name {get; set;}
    ...//other attributes from this table (not relevant)
}
public class EmployeeProfile
{
    public int profileID {get; set;} //primary key
    public int employeeID {get; set;}
    public string favoritemovie {get; set;}
    ...//other attributes from this table (not relevant)
}

数据库中与EmployeeProfileEmployee的关系为1 - 1。在我的应用程序中,我想创建一个组合实体,如下所示:

public class Employee
{
    public int employeeID {get; set;}
    public string name {get; set;}              //taken from Employee Table
    public string favoritemovie { get; set; }   //taken from EmployeeProfile table
}

我该怎么做?我听说过实体拆分,但要求表具有相同的主键。

2 个答案:

答案 0 :(得分:0)

EF已经为您创建了关系。您应该能够通过Employee实体访问EmployeeFile(即employee.EmployeeProfile [0]获取与您检索到的员工enitty相关的员工配置文件)

答案 1 :(得分:0)

正如RandomAsianGuy所述,从员工实体跳转到个人资料实体是微不足道的。

但是,如果您坚持创建此合并实体,那么您正在寻找的是实体框架中的每个类型的表(TPT)映射继承,使用Employee作为基类并从Employee派生EmployeeProfile。

以下是使用EDMX进行TPT继承的MSDN演练:

http://msdn.microsoft.com/en-us/data/jj618293