Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provide expression to subquery

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;
}
like image 571
SiberianGuy Avatar asked Oct 11 '22 07:10

SiberianGuy


1 Answers

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.

like image 51
Slauma Avatar answered Oct 14 '22 04:10

Slauma