c# - LINQ 大于/小于在查询中不工作
问题描述
var query = db.Products.Where(p => p.Cost == 10M);
工作得很好,并返回正确的结果列表。
var query = db.Products.Where(p => p.Cost > 10M);
抛出异常:
The LINQ expression 'DbSet<Product>.Where(p => p.Cost > (Nullable<decimal>)10)' could not be translated.
显然 C# 生成的脚本不能在 SQL 中执行,但为什么不呢?这是一个有效的 SQL 查询
public class Product
{
public int ProductID {get;set;}
[Required]
[StringLength(40)]
public string ProductName {get;set;}
[Column("UnitPrice", TypeName="money")]
public decimal? Cost {get;set;}
}
public class Northwind: DbContext
{
public DbSet<Category> Categories {get;set;}
public DbSet<Product> Products {get;set;}
}
EFCore 3.1.2、.NET Core 3.1.1
解决方案
看起来p.Cost
是一个decimal?
. 在这种情况下,您可以使用null 合并运算符。
var query = db.Products.Where(p => (p.Cost ?? 0) > 10M);
推荐阅读
- tcl - 使用 tcl 脚本将数据提取到不同的文件
- xamarin - 无法从 Visual Studio for mac 中的 nuget 包安装 ReactiveUI
- ios - 滚动期间崩溃,因为边界返回为零
- z3 - 使用 SMT 2 输入格式在 Z3 中的 BitVec 中计数
- c# - 如何在 C# 中手动验证自签名证书?
- google-cloud-platform - Google Cloud Stackdriver 监控 - 计算引擎磁盘空间
- python - 注销时使 AWS Cognoto 令牌无效
- php - PHP 的 symlink() 可以创建相对符号链接吗?
- java - 使用 JDBC 以引用顺序创建外键和索引
- css - 在响应视图上禁用粘滞侧边栏