简体   繁体   中英

Include navigation properties of inherited entity

I'm using entity framework, eager loading and I'm trying to load a part of my graph. I have Person table inherited by Candidate and Trainer, and I have a problem when someone is both, Trainer and Candidate (NOTE: Trainer and Candidate don't have any additional properties, only primary key inherited from Person).

This is my query:

RequestInfo ri = context.RequestInfo.Include(x => x.Request).Include(x => x.TeamName).Include(x => x.Sender)
                .Include(x => x.TrainingLanguage).Include(x => x.TrainingLocation).Include(x => x.CcPerson.Select(p => p.Person))
                .Include(x => x.Request.Select(c => c.Candidate))
                .Include(x => x.Request.Select(c => c.Candidate).Select(ct => ct.CandidateType))
                .Include(x => x.Request.Select(c => c.Candidate.CandidateType.Select(cwp => cwp.CandidateWorkPresence)))
                .Where(x => x.Id == r.Id).Single();

It probably might be better, but what I have as a problem is, when some person is Candidate and Trainer i get following exception:

All objects in the EntitySet 'EmployeesTrainingEntities.Person' must have unique primary keys. However, an instance of type 'EmployeesTrainingModel.Candidate' and an instance of type 'EmployeesTrainingModel.Trainer' both have the same primary key value, 'EntitySet=Person;PersonId=5'.

I try to find some solution for the problem, but i didn't have luck, and I saw that many people have this problem. Maybe I'm missing something, so if someone has some solution, suggestion,... it's welcome. If it's necessary I will add a photo that contains a part of my model which I'm trying to load.

EDIT: Model contains RequestInfo entity which has common information about requests for training. RequestInfo has collection of Requests , Sender who is Person and collection of CcPersons (persons that will follow the training). Request contains Candidate .

Solution: I found out solution of my problem. When I have person who is Trainer and Candidate , what I do is inheritance overlapping, and it seems that EntityFramework doesn't allow inheritance overlapping. So, I replaced inheritance relationship with association, and now it works properly.

I don't see the point in creating two extra entities that inherit from person if they dont have any additional properties.

Why not just edit the Person table, to include an enum [flag] property for PersonRole . That way you can assign multiple roles to one user and store them in an int.

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