c# - 带有 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.
我的第一个想法是它与客户端评估有关。但是在客户端根本没有工作可做。这只是一个简单的查询,应该只从一个表中选择记录。
解决方案
ElementAt(0)
不是有效的 LINQ 可翻译函数。在这种情况下,您应该使用SingleOrDefault()
orSingle()
推荐阅读
- javascript - 如何使用 HTML 输入在 JavaScript 中按键过滤字典/对象?
- r - 有没有办法读取 R 中的整个文件文件夹,然后导出为 1 个 excel 工作簿,每个文件输出为一张表?
- java - 读取文件时出错:线程“main”中的异常 java.util.NoSuchElementException:找不到行
- javascript - 根据另一个组件的状态更改 React 组件的可见性
- javascript - GainNode.gain.value 返回属性增益未定义?
- moving-average - 函数 iMA 正在返回与预期不同的返回值 (MQL5)
- language-agnostic - 处理从 0**1e-15 到 1e-15**1e-15 时出现的不连续性的优雅方式
- javascript - 选择 onchange 标记不运行我的 Javascript 函数
- javascript - 来自组件的角度事件监听器
- ruby - 在标量上分布数组:飞溅还是不飞溅?