首页 > 解决方案 > 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

标签: c#linqentity-framework-core

解决方案


看起来p.Cost是一个decimal?. 在这种情况下,您可以使用null 合并运算符

var query = db.Products.Where(p => (p.Cost ?? 0) > 10M);

推荐阅读