EF Code First Mapping Multiple Classes to One Table
I've got quite a complex database that I want to map to code first but I am having a problem with a table that needs to be split out into two separate classes.
A basic example of the tables structure is as follows:
Site
----
Id
Name
Person
------
Id
Name
Dob
Address
Rank
Age
SiteId
PersonRoleLink
--------------
PersonId
RoleId
Role
----
Id
Name
Basically a Site has many people and each person can have many roles.
Depending on the role the person has depends what properties are populated.
Ideally I would like a class structure as follows:
public class Site {
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
public virtual ICollection<Manager> Managers { get; set; }
}
public class PersonBase {
public int Id { get; set; }
public string Name { get; set; }
public virtual Site Site { get; set; }
}
public class Customer : PersonBase {
public string Name { get; set; }
public DateTime Dob { get; set; }
}
public class Employee: PersonBase {
public int Age { get; set; }
}
public class Manager: PersonBase {
public int Rank { get; set; }
}
Where Customer
, Employee
and Manager
all come from the Person
table and 开发者_如何学运维are dependant on the relevant link in the PersonRoleLink
table.
So when I call something like Site.Managers
the rows in the Person
table returned are the ones with the correct SiteId and with a link to a Role
called 'Manager'
Is this structure possible in code first? If so how is the mapping for this achieved and if not are there any viable alternatives to this structure?
Thanks
It is not possible with EF because it is data driven mapping and EF code first doesn't support it except single exception: Table per hierarchy inheritance mapping where value of single column in mapped table can differ mapped sub entities. In your case the value differing the type of entity is two relations away. Moreover one record from person table can represent multiple entity instances. That is another problem because these instances will not have unique key and EF will not be able to do that.
Generally your supposed object model is wrong because you can have single person who is employee and manager. It should not result in two different "Person" objects. User Person
directly with navigation property to roles and create helper methods to get Managers, Employees and Customers.
精彩评论