LINQ (EF) query property of list of grandchildren as list

43 Views Asked by At

Trying to add a projection where I get Ids from a list from a list.

Given a relationship like:

-> accounts

--> users

---> cars

----> id

Single level, ids of users, works:

builder.Entity<AccountModel>()
.WithProjection(x => x.UsersIds, x => x.Users.Select(y => y.Id).ToList());

But I need ids of cars, and I can't seem to put together the right query today:

    .WithProjection(x => x.CarsIds, x => x.Users.SelectMany(y => y.Cars.Select(z => z.Id)).ToList());

Trying throws an error like:

The LINQ expression 'y => y.Cars.Select(z => z.Id)' could not be translated

Alternative example as suggested by Danyliv:

_context.Accounts.Select(a => new 
{
    CarsIds = a.Users.SelectMany(y => y.Cars.Select(z => z.Id)).ToList()
})

The LINQ expression 'x => x.Users' could not be translated.

I am trying to avoid pulling in the entire list of users and cars when querying the accounts, but I want to know what ids for each of these things exist at the account level.


Update

Tried:

   .WithProjection(x => x.CarsIds, x => x.Users.SelectMany(y => y.Cars).Select(z => z.Id).ToList())

The LINQ expression 'y => y.Cars' could not be translated

So maybe SelectMany doesn't play nice with EF?

0

There are 0 best solutions below