首页 > 解决方案 > 带有 where 条件的 EFCore 3 引发异常

问题描述

这很奇怪。我有一个看起来像这样的模型:

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; }
}

请注意,为清楚起见,删除了一些其他功能。现在,我像这样映射它:

(b 是 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);

我需要从数据库中获取一些值:

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

目前,一切正常。当我在调试窗口中预览结果时,我可以看到只有一条我预期的记录。但是,问题就在这里:

UserLimit ul = result.ElementAt(0);

虽然有对象,但我得到一个例外:

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.

我的第一个想法是它与客户端评估有关。但是在客户端根本没有工作可做。这只是一个简单的查询,应该只从一个表中选择记录。

标签: c#ef-core-3.1

解决方案


ElementAt(0)不是有效的 LINQ 可翻译函数。在这种情况下,您应该使用SingleOrDefault()orSingle()


推荐阅读