LINQ ArgumentException due to AnonymousObject

.net .net-core c# entity-framework-core linq

Question

I am trying to Union two IQueryables of the same type but am hit with the following error

An exception of type 'System.ArgumentException' occurred in System.Private.CoreLib.dll but was not handled in user code: 'The input sequence must have items of type 'MyProject.Data.Entities.Project', but it has items of type 'Microsoft.EntityFrameworkCore.Query.Internal.AnonymousObject'.'

Basically I am taking a list of Projects and separating those that have Any() ProjectActivities out into their own list - I am then sorting them by the Activity Name before finally attempting to Union the original Projects back in.

My code was originally:

IQueryable<Project> projectsWithActivities = projects
            .Where(x => x.ProjectActivities.Any())
projects = projectsWithActivities
                    .OrderBy(u => u.ProjectActivities
                        .OrderBy(p => p.Activity.Name)
                    .FirstOrDefault().Activity.Name)
                    .AsQueryable()
                    .Union(projects);

Note that projects is an existing IQueryable<Project> passed in as a method argument.

After some research I believed that the cause of my error was because the Where was causing projectsWithActivities to become an AnonymousObject and to overcome this issue I had to Select into a new Project Object so I changed my code to:

IQueryable<Project> projectsWithActivities = projects
            .Where(x => x.ProjectActivities.Any())
            .Select(x => new Project(){Id = x.Id, SomeProperty = x.SomeProperty,
                etc etc});

However, this made no difference, I am still faced with the above error.

Also if you are wondering why I am separating a list of Projects out and then trying to merge them back in, it's because some Projects do not have any ProjectActivities and therefore whenever I attempt to sort by the Activity Name it falls over on a null reference.

Could somebody please shed some light on what I am doing wrong - I am still very much learning basic Linq and so I am completely stumped on this one.

Thanks in advance!

1
0
12/4/2018 10:31:17 PM

Popular Answer

If you get this error in a Union or Concat, it probably means there is an error with one of the subqueries. Pull the subquery out of the statement and evaluate the results in the debugger to see what the error is.

0
11/15/2019 7:28:07 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow