2

我正在尝试找到将 union 与 linq 结合使用的最佳方法。

目前我必须编译具有相同签名的查询:

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

在我的存储库类上,我正在做一些链接:

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

但是有些事情告诉我联合应该在编译的查询中。像这样的东西:(这段代码不会编译)

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));

有没有办法做到这一点?

4

1 回答 1

3

尝试:

 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))
    ));
于 2011-04-21T14:53:21.280 回答