简体   繁体   English

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

[英]Mapping two tables with different primary keys to one entity

I'm making an application using EF on a legacy database. 我正在旧数据库上使用EF制作应用程序。 In the database there are two tables I am concerned with. 在数据库中,我关注两个表。 The structure (in C# form) looks like this: 结构(以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)
}

There is a 1 - 1 relationship with EmployeeProfile and Employee in the database. 数据库中与EmployeeProfileEmployee之间存在1-1关系。 In my application, I'm wanting to create a combined entity, like this: 在我的应用程序中,我想创建一个组合实体,如下所示:

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
}

How can I do this? 我怎样才能做到这一点? I've heard of entity splitting but that requires the tables to have the same primary key. 我听说过实体拆分,但是这要求表具有相同的主键。

EF already creates the relationships for you. EF已经为您创建了关系。 You should be able to access EmployeeFile via the Employee entity (ie employee.EmployeeProfile[0] grabs the employee profile related to the employee enitty you retrieved) 您应该能够通过Employee实体访问EmployeeFile(即employee.EmployeeProfile [0]会获取与您检索到的雇员enitty相关的雇员资料)

As RandomAsianGuy stated, it's trivial to jump to the profile entity from the employee entity. 正如RandomAsianGuy所说,从员工实体跳到个人资料实体是微不足道的。

If you insist on creating this merged entity, however, what you're looking for is table-per-type (TPT) mapping inheritance in Entity Framework, using Employee as the base class and deriving EmployeeProfile from Employee. 但是,如果您坚持要创建此合并实体,那么您要寻找的是Entity Framework中的按类型表(TPT)映射继承,使用Employee作为基类并从Employee派生EmployeeProfile。

Here is an MSDN walk-through of TPT inheritance using EDMX: 这是使用EDMX的TPT继承的MSDN演练:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM