.net - 为子查询提供表达式

标签 .net entity-framework linq-to-entities

我有以下 LINQ To Entities 查询(以简化形式):

ctx.BattlesUsers.Where(bu => bu.DateTime == ctx.BattlesUsers.
   Where(BattleUserSpecifications.BattleIdIsEqualTo(bu.BattleId)).
   Max(bu1 => bu1.DateTime));

引发异常“内部 .NET Framework 数据提供程序错误 1025。”。

这里的问题是我的规范调用。此问题的通常解决方案是将规范表达式调用移出查询并将表达式直接传递给 Where。但它在这里不起作用,因为我需要将 bu.BattleId 传递给表达式。

更新。

这是 BattleIdIsEqualTo 的代码:
public static Expression<Func<Model.Entities.BattleUser, bool>> UserIdIsEqualTo(long userId)
{
   return bu => bu.UserId == userId;
}

最佳答案

如果我假设 BattleUserSpecifications.BattleIdIsEqualTo(int battleId)看起来很像 return bu => bu.BattleId == battleId;我使用新规范得到以下结果:

public static class BattleUserSpecifications
{
    public static Expression<Func<BattleUser, bool>> FilterByDateTime(
        IQueryable<BattleUser> battleUsers)
    {
        return bu => bu.DateTime == battleUsers
            .Where(bu1 => bu1.BattleId == bu.BattleId)
            .Max(bu2 => bu2.DateTime);
    }
    //...
}

然后以下查询有效:
var query = ctx.BattlesUsers.Where(
    BattleUserSpecifications.FilterByDateTime(ctx.BattlesUsers));

这可能不是您想要的,只是一种解决方法。我可以重现您在原始查询中遇到的异常。 “内部错误”看起来像是代码在内部遍历了一条相当意外的路径,很可能只有 MS/EF 团队才能真正回答出了什么问题。您可能必须重写查询才能获得所需的结果。

关于.net - 为子查询提供表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6968143/

相关文章:

c# - 如何管理 MVC Controller 中所有未处理的错误

c# - SelectNodes 不适用于 stackoverflow 提要

c# - MySql.Data.MySqlClient.MySqlException : There is already an open DataReader associated with this Connection which must be closed first

性能 linq group by 带计数

c# - 不在引用的程序集中键入 Foo,但我使用的是扩展类型 Foo 的类型 Bar

C# - LINQ - GPS经纬度的最短距离

c# - Like 运算符或在 LINQ to Entities 中使用通配符

c# - 导出当前gridview数据

.net - 将工作单元和存储库模式与 Entity Framework 结合使用的好处

linq-to-entities - IQueryable Lambda 投影语法