using union on linq compiled queries

1.6k Views Asked by At

I'm trying to find the best way to use union with linq.

currently I have to compiled queries with the same signature:

public Func<DataContext, int, IQueryable<Item>> Query1
public Func<DataContext, int, IQueryable<Item>> Query2

and on my repository class i'm doing something link this:

using (DataContext context = new DataContext(ConnectionString)) {
    return _queries.Query1(context, id).Union(
        _queries.Query2(context, id));
}

but something tells me that the union should be inside the compiled query. Something like this: (this code won't compile)

public Func<DataContext, int, IQueryable<Item>> Query1 = 
    CompiledQuery.Compile((DataContext context, int id) =>
    from table1 in context.GetTable<Table1>()
    where table1.foreignId = id
    select new Item(table1)
    union
    from table2 in context.GetTable<Table2>()
    where table2.foreignId = id
    select new Item(table2));

Is there a way to achieve this?

1

There are 1 best solutions below

0
On BEST ANSWER

Try:

 public Func<DataContext, int, IQueryable<Item>> Query1 = 
    CompiledQuery.Compile((DataContext context, int id) =>
      (from table1 in context.GetTable<Table1>()
      where table1.foreignId = id
      select new Item(table1))
    .Union(
      (from table2 in context.GetTable<Table2>()
      where table2.foreignId = id
      select new Item(table2))
    ));