.SelectMany () and retrieving data from more than one related table.

This query returns the employee identifier, name, company identifier, company name and company city. I am missing an employee email address (email address stored in the EmployeeEmailAddress table) and employee phone numbers (phone number stored in the EmployeePhoneNumbers table).

I needed to add .SelectMany () to get a relationship with the parent company and access the company id, name and city. However, now I cannot access any properties not found in the PersonOrgMap table. I can not go to other tables. Removing .SelectMany () allows me to navigate through other tables, but I lose access to information about the parent company.

var employees = Contacts.Where(c => c.ContactAttributes
.Any (ca => ca.AttributeID == 1153))
.SelectMany (x => x.ChildPersonOrgMaps)
.Select (c => new { employeeId = c.Child.ContactID,
          c.Child.FirstName,
          c.Child.LastName,
          companyId = c.ParentContactID,
          c.Parent.OrganizationName,
          c.Parent.City
        }
         )
.OrderBy (c =>c.LastName ).ThenBy(x => x.FirstName)
.Dump();
+5
4

. :

from c in Contacts
where c.ContactAttributes.Any (ca => ca.AttributeID == 1153))
from om in c.ChildPersonOrgMaps
...

c om. # SelectMany, , "" . - LINQPad, , .

+5

, SelectMany(), "" "":

.SelectMany(x => x.ChildPersonOrgMaps, (x, c) => new { x, c })
.Select(xc => new 
{ 
    xc.x.Attribute1,
    xc.x.Attribute2,
    xc.c.Child.Attribute3,
    xc.c.Attribute4
});
+16

Joe Albahari - . ( ), , .

, , , EF .

var employees = Contacts.Where(c => c.ContactAttributes 
.Any (ca => ca.AttributeID == 1153)) 
.SelectMany (x => new { Parent = x, Child = x.ChildPersonOrgMaps })
// etc
0

LINQ , , . , , , , , , , LINQ.

var persons = new [] {"John's", "Mike's", "Albert's"};
var objects = new [] {"car", "house", "bicycle"};
var colors  = new [] {"red", "blue", "green", "yellow"};


var firstPair = persons.SelectMany(_ => objects, (p, o) => new {
   Person = p,
   Object = o
});

var secondPair = firstPair.SelectMany(_ => colors, (fp, c) => new {
   Person = fp.Person,
   Object = fp.Object,
   Color = c
});

LINQ Pad, .

0

All Articles