2

我有多个要联合在一起的查询,然后编译整个事情。未编译的查询运行良好,但“InvalidOperationException:'UserQuery+Foo' 的成员访问 'Int32 Id' 在类型 'System.Linq.IQueryable`1[UserQuery+Foo] 上不合法。” 编译和运行相同的查询时会引发异常。

我该如何解决?

void Main()
{
    var db = new MyDataContext( "..." );

    Expression < Func < DataContext, int, IQueryable < Foo > > > queryExpression = (DataContext dc, int unused) =>
        from ab in GetA(dc).Union( GetB(dc) )
        group ab by new { ab.Id, ab.Name } into grp
        select new Foo
        {
            Id = grp.Key.Id,
            Name = grp.Key.Name,
            Total = grp.Count()
        };

    var final = CompiledQuery.Compile ( queryExpression );

    var result1 = queryExpression.Compile () (db, 0);  // calling the original query works fine
    var result2 = final (db, 0);            // calling the compiled query throws an exception
}

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Total { get; set; }
}

IQueryable<Foo> GetA( DataContext db )
{
    return from b in db.GetTable<Bar>()
    where b.IsActive
    select new Foo { Id = b.Id, Name = b.Name };
}

IQueryable<Foo> GetB( DataContext db )
{
    return from b in db.GetTable<Bar>()
    where !b.IsActive
    select new Foo { Id = b.Id, Name = b.Name };
}

编辑

看起来联合和分组无关紧要。从查询中删除这些元素在编译时仍然会导致异常:

    Expression < Func < DataContext, int, IQueryable < Foo > > > queryExpression = (DataContext dc, int unused) =>
        from a in GetA(dc)
        select new Foo
        {
            Id = a.Id,
            Name = a.Name,
            Total = 42
        };

将调用替换为GetA(dc)withdc.GetTable<Bar>()并添加 where 子句可解决问题。

那么,对于已编译的查询,像这样将单独的查询连接在一起是不可能的吗?

编辑#2

詹姆斯的回答一针见血。简化查询进一步揭示了根本问题:

    Expression < Func < DataContext, int, IQueryable < Foo > > > queryExpression = (DataContext dc, int unused) =>
        from a in GetA(dc)
        select a;

此查询抛出NotSupportedException: Method 'System.Linq.IQueryable``1[UserQuery+Foo] GetA(System.Data.Linq.DataContext)' has no supported translation to SQL.

将对 GetA 的调用拉到单独的变量赋值中,然后在查询中使用该变量会引发InvalidOperationException: Sequence contains more than one element异常。

4

2 回答 2

1

我有同样的问题,似乎对我有用的是分离出一个返回 IQueryable<> 的内联静态方法调用,以便我将这个延迟查询存储到一个变量中并引用它。

我认为这是 Linq to SQL 中的一个错误,但至少有一个合理的解决方法。

于 2010-10-26T15:58:25.603 回答
0

我的猜测是 linq 编译器不理解返回 IQueryable 的方法。

要编译它,这些方法可能必须返回某种形式的 Expression<>。

于 2010-07-08T18:16:59.890 回答