LINQ大于/小于在查询中不起作用 [英] LINQ greater/less than not working in query
问题描述
var query = db.Products.Where(p => p.Cost == 10M);
可以很好地工作并返回正确的结果列表. var query = db.Products.Where(p => p.Cost> 10M);
引发异常:
var query = db.Products.Where(p => p.Cost == 10M);
works perfectly fine and returns the correct list of results.
var query = db.Products.Where(p => p.Cost > 10M);
throws an exception:
LINQ表达式'DbSet< Product> .Where(p => p.Cost>(Nullable< decimal>)10)'无法翻译.
很明显,C#生成的脚本无法在SQL中执行,但是为什么不呢?那是有效的SQL查询
Obviously the script being generated by C# can't be executed in SQL but why not? That is a valid SQL query
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
EFCore 3.1.2, .NET Core 3.1.1
推荐答案
看起来 p.Cost
是一个十进制?
.在这种情况下,您可以使用 null合并运算符.
It looks like p.Cost
is a decimal?
. In that case you can use the null coalescing operator.
var query = db.Products.Where(p => (p.Cost ?? 0) > 10M);
这篇关于LINQ大于/小于在查询中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!