简体   繁体   中英

Mapping two tables with different primary keys to one entity

I'm making an application using EF on a legacy database. In the database there are two tables I am concerned with. The structure (in C# form) looks like this:

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. 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. 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)

As RandomAsianGuy stated, it's trivial to jump to the profile entity from the employee entity.

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.

Here is an MSDN walk-through of TPT inheritance using EDMX:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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