5

I have the following LINQ To Entities query (in simplified form):

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

which throws exception "Internal .NET Framework Data Provider error 1025.".

The problem here is my specification call. The usual solution for this problem is to move specification expression call out of query and pass expression directly to Where. But it won't work here as I need to pass bu.BattleId to the expression.

Update.

Here is the code of BattleIdIsEqualTo:

public static Expression<Func<Model.Entities.BattleUser, bool>> UserIdIsEqualTo(long userId)
{
   return bu => bu.UserId == userId;
}
SiberianGuy
  • 24,674
  • 56
  • 152
  • 266

2 Answers2

3

If I assume that BattleUserSpecifications.BattleIdIsEqualTo(int battleId) looks similar like return bu => bu.BattleId == battleId; I get the following working with a new specification:

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);
    }
    //...
}

Then the following query works:

var query = ctx.BattlesUsers.Where(
    BattleUserSpecifications.FilterByDateTime(ctx.BattlesUsers));

This is probably not what you want and only a workaround. I could reproduce the exception you have with your original query. An "internal error" looks like the code is traversing a rather unexpected path internally and it's likely that only MS/EF team can really answer what's going wrong. You probably have to rewrite your query to get the result you want.

Slauma
  • 175,098
  • 59
  • 401
  • 420
1

I'm going to give this another stab. If your goal is to get the most current battleusers for each battleid then you could use this query

    ctx.BattlesUsers.GroupBy(bu => bu.BattleId)
    .Select(bug => bug.OrderByDescending( bu => bu.DateTime).FirstOrDefault())

If you wanted to then use an expression function to filter it at this point you could, but you would need to get your userid externally and then pass it in through Where clause tacked on to the end.

Jack Woodward
  • 455
  • 4
  • 20