表达式树lambda不得包含空传播运算符 [英] an expression tree lambda may not contain a null propagating operator
问题描述
问题:以下代码中的行price = co?.price ?? 0,
给了我上面的错误.但是,如果我从co.?
中删除?
,则可以正常工作.我试图遵循此MSDN示例他们在select new { person.FirstName, PetName = subpet?.Name ?? String.Empty };
行上使用?
的位置因此,似乎我需要了解何时将?
与??
一起使用,何时不使用.
Question: The line price = co?.price ?? 0,
in the following code gives me the above error. but if I remove ?
from co.?
it works fine. I was trying to follow this MSDN example where they are using ?
on line select new { person.FirstName, PetName = subpet?.Name ?? String.Empty };
So, it seems I need to understand when to use ?
with ??
and when not to.
错误:
表达式树lambda不得包含空传播运算符
an expression tree lambda may not contain a null propagating operator
public class CustomerOrdersModelView
{
public string CustomerID { get; set; }
public int FY { get; set; }
public float? price { get; set; }
....
....
}
public async Task<IActionResult> ProductAnnualReport(string rpt)
{
var qry = from c in _context.Customers
join ord in _context.Orders
on c.CustomerID equals ord.CustomerID into co
from m in co.DefaultIfEmpty()
select new CustomerOrdersModelView
{
CustomerID = c.CustomerID,
FY = c.FY,
price = co?.price ?? 0,
....
....
};
....
....
}
推荐答案
您引用的示例使用LINQ to Objects,其中查询中的隐式lambda表达式转换为 delegates ...而您使用的是EF或类似版本,并带有IQueryable<T>
查询,其中lambda表达式将转换为表达式树.表达式树不支持空条件运算符(或元组).
The example you were quoting from uses LINQ to Objects, where the implicit lambda expressions in the query are converted into delegates... whereas you're using EF or similar, with IQueryable<T>
queryies, where the lambda expressions are converted into expression trees. Expression trees don't support the null conditional operator (or tuples).
只需按照旧方法即可:
price = co == null ? 0 : (co.price ?? 0)
(我相信在表达式树中可以使用null-coalescing运算符.)
(I believe the null-coalescing operator is fine in an expression tree.)
这篇关于表达式树lambda不得包含空传播运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!