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!
.AsQueryable()
? Does it work if you remove it?OrderBy
returns anIEnumerable
and so I thought the issue was because I was trying toUnion
anIEnumerable
and anIQueryable
but no unfortunately it does not work with or without it.AsQueryable
, what is the exact error?AsQueryable
I get the 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.Entities.Project', but it has items of type 'Microsoft.EntityFrameworkCore.Query.Internal.AnonymousObject'.'