Search code examples
c#entity-frameworklinqentity-framework-core

c# linq - SelectMany - An expression tree lambda may not contain a dictionary initializer


I am trying to fetch records from the table and converting it into dictionary but getting error while casting into Dictionary<int, List<WorkpaperClientDetail>> using selectmany operator.

Getting error - An expression tree lambda may not contain a dictionary initializer.

var asd = uow.WorkpaperRepo.GetAllNoTracking(expression)
    .SelectMany(wps => new Dictionary<int, List<WorkpaperClientDetail>>
    {
        [wps.WorkpaperId] = wps.AccountMap.AccountMappings.Select(y => new WorkpaperClientDetail
        {
            AccountName = y.ClientAccount.Description,
            AccountNumber = y.ClientAccount.Code
        }).ToList()
    }).ToDictionary(d => d.Key, d => d.Value);

Solution

  • A dictionary initializer that starts with [wps.WorkpaperId] = wps.AccountMap ... ? I don't know what you are trying to do here but this should work as expected:

    Dictionary<int, List<WorkpaperClientDetail>> asd = uow.WorkpaperRepo.GetAllNoTracking(expression)
        .Select(wps => new{ wps.WorkpaperId, ClientList = wps.AccountMap.AccountMappings
            .Select(y => new WorkpaperClientDetail
            {
                AccountName = y.ClientAccount.Description,
                AccountNumber = y.ClientAccount.Code
            })
            .ToList() })
       .ToDictionary(x => x.WorkpaperId, x => x.ClientList);