Search code examples
c#entity-frameworklinqlinq-to-entitiesentity-framework-core

SelectMany applied to 3 lists


I need to create a list of objects, OrganizationEnrolment, created using 3 Entity Framework entities (User, EnrolmentType and OrganizationEnrolment):

List<OrganizationEnrolment> organizationEnrolments = 
  context.Organizations
  .SelectMany(x => context.Users)
  .SelectMany(x => context.EnrolmentTypes)
  .Select(y => new OrganizationEnrolment {
     EnrolmentType = enrolmentType
     Organization = organization,
     User = user
   })

My problem is after having the SelectMany how to get the enrolmentType, organization and user from the 3 joined table? Note that the following code:

EnrolmentType = enrolmentType,
Organization = organization,
User = user

is not working because I do not have the variables enrolmentType, organization and user.


Solution

  • You can use query syntax to get all those variables:

    from o in context.Organizations
    from u in context.Users
    from et in context.EnrolmentTypes
    select new OrganizationEnrolment {
         EnrolmentType = et
         Organization = o,
         User = u
       }
    

    Each local range variable will be visible in select statement.

    Lambda syntax (checked with EF6):

    context.Organizations.SelectMany(
              o => context.Users.SelectMany(
                  u => context.EnrolmentTypes.Select(
                      et => new OrganizationEnrolment {
                           EnrolmentType = et
                           Organization = o,
                           User = u
                      })
                  )
             )