Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return IQueryable containing 2 Subclasses

Tags:

c#

linq-to-sql

Can you return IQueryable which is composed of two or more different subclasses ? Here's my attempt to show what I mean. It throws the error:

System.NotSupportedException: Types in Union or Concat have members assigned in different order..

var a = from oi in db.OrderItems
        where oi.OrderID == ID
            && oi.ListingID != null
        select new OrderItemA {
            // etc
        } as OrderItem;

var b = from oi in db.OrderItems
        where oi.OrderID == ID
            && oi.AdID != null
        select new OrderItemB {
            //etc
        } as OrderItem;

return a.Concat<OrderItem>(b);
like image 607
Chris Porter Avatar asked Dec 31 '22 06:12

Chris Porter


1 Answers

Try doing the concat on IEnumerable instead of IQueryable:

return a.AsEnumerable().Concat(b.AsEnumerable());

If you need an IQueryable result you could do this:

return a.AsEnumerable().Concat(b.AsEnumerable()).AsQueryable();

Doing this will force the concat to happen in-memory instead of in SQL, and any additional operations will also happen in-memory (LINQ To Objects).

However, unlike the .ToList() example, the execution should still be deferred (making your data lazy loaded).

like image 172
Joshua Sjoding Avatar answered Jan 01 '23 19:01

Joshua Sjoding