简体   繁体   中英

How to select a collection based on condition in EF Core?

I have an object that has two lists, and I need to select one of them based on a condition, like so:

    .Set<Person>()
    .Select(x => 
            Employees = x.IsManager ? x.WorkerList1 : x.WorkerList2

Both WorkerList1 and WorkerList2 are collections of the same type.

I tried unioning/concatinating the lists and it throws an error (cannot translate it).

I tried to select an intermediateQueryView object, like so:

    .Set<Person>()
    .Select(x => 
            Employees = x.IsManager 
                 ? x.WorkerList1.Select(x => new EmployeeView { //..assign properties here }) 
                 : x.WorkerList2.Select(x => new EmployeeView { //..assign properties here })

it also fails to translate. Is there any way to achieve this?

I am using MSSQL provider.

Have you thought to split the queries?

var queryForManagers = queryable.Where(x => x.IsManager);
var queryForNotManagers = queryable.Where(x => !x.IsManager);

// now you can map and concat items independently...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM