Linq SelectMany includes parent

I have the following three Linq To Sql objects: Location, Institution, and Building.

The location table is simply LocationId and LocationTypeId.

The institution and the building receive both identifiers from the Location table in a one-to-one relationship, and the Institution table has a one-to-one relationship with the Building table.

I am trying to return all location records for the institution and all its children. The following query returns what I need, except that there is no record of the location of the parent organization.

var query = dc.Locations.SelectMany(l => l.Institutions, (loc, inst) => new { loc, inst })
                        .SelectMany(i => i.inst.Buildings, (locInst, bld) => bld.Location );

How to include parent element together with child elements?

ERD with corresponding columns

UPDATE:

I can get the records I want if I use the join in the original location request, but I'm still wondering if this is the best solution. Here is the code with Union.

IQueryable<Location> locations = dc.Locations;

locations.SelectMany(l => l.Institutions, (loc, inst) => new { loc, inst })
         .SelectMany(i => i.inst.Buildings, (locInst, bld) => bld.Location)
         .Union(locations);
+4
source share

Source: https://habr.com/ru/post/1620436/


All Articles