EFCore 3 with where condition throws exception

49 Views Asked by At

this is weird. I have a model that looks like that:

public class UserLimit: IDbItem //IDbItem has just Id field
{
    public virtual Guid Id { get; set; }
    public virtual Guid UserId { get; set; }
    public virtual LimitTypes LimitType { get; set; } //some enum
    public virtual DateTimeOffset? ValidUntil { get; protected set; }
    int CurrentLimit { get; set; }
    int PreviousLimit { get; set; }
}

Note that there are some other functinos removed for clarity. Now, I map it like that:

(b is EntityTypeBuilder)

b.ToTable("users_limits")
.HasKey(x => new { x.UserId, x.LimitType });

b.Property(x => x.UserId).IsRequired();
b.Property(x => x.LimitType).IsRequired().HasConversion(typeof(int));
b.Property(x => x.ValidUntil);
b.Property<int>("CurrentLimit").IsRequired().UsePropertyAccessMode(PropertyAccessMode.Field);
b.Property<int>("PreviousLimit").IsRequired().UsePropertyAccessMode(PropertyAccessMode.Field);

And I need to get some values from DB:

var result = dbContext.UserLimits.AsQueryable()
            .Where(x => x.UserId == userId && x.LimitType == limitType);

For now, everything works fine. When I preview the result in debug window, I can see that there is only one record that I expected it to be. But, the problem is here:

UserLimit ul = result.ElementAt(0);

Althaough there is the object, I get an exception:

Processing of the LINQ expression 'DbSet<UserLimit>
    .Where(x => x.UserId == __userId_0 && (int)x.LimitType == (int)__limitType_1)
    .ElementAt(__p_2)' by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.

My first thought was that it has something to do with client side evaluation. But there is no job to do at client side at all. It's just simple query that should select record from only one table.

1

There are 1 best solutions below

0
On BEST ANSWER

ElementAt(0) is not a valid LINQ-translatable function. You should use SingleOrDefault() or Single() in this case