Multiple Include/ThenInclude causing duplicates in EF Core

.net-core entity-framework entity-framework-core sql-server

Question

Ok, so I have a table Building which includes all Persons in that building. However each Person has a profession which is a entity in itself that is added to the Person entity depending what is available.

var data = _dbcontext.Building
        .Where(m => m.BuildingId == buildingId)
        .Include(x => x.Person).ThenInclude(x => x.Doctor)
        .Include(x => x.Person).ThenInclude(x => x.Teacher)
        .Include(x => x.Person).ThenInclude(x => x.Farmer)
        .Include(x => x.Person).ThenInclude(x => x.Prostitute);

This is how I found to do it online, but it seems to literally be including the Person entity 4 times, so I have tons of duplicates. I really only want it once, but I want to left join the profession entities as available.

The Foreign keys are all setup properly and I used EF to create my models. Here is what the Person entity looks like:

public partial class Person {
    public int PersonId { get; set; }
    public int? DoctorId { get; set; }
    public int? TeacherId { get; set; }
    public int? FarmerId { get; set; }
    public int? ProstituteId { get; set; }
    public int BuildingId { get; set; }

    public Doctor Doctor { get; set; }
    public Teacher Teacher { get; set; }
    public Farmer Farmer { get; set; }
    public Prostitute Prostitute { get; set; }
}
1
1
6/20/2017 6:14:47 AM

Popular Answer

var data = _dbcontext.Person
    .Where(p => p.BuildingId == buildingId)
    .Include(p => p.Building)
    .Include(p => p.Doctor)
    .Include(p => p.Teacher)
    .Include(p => p.Farmer)
    .Include(p => p.Prostitute)
    .OrderBy(p => p.Building;
0
6/18/2018 9:46:28 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow