行 price = co?.price ?? 0,
在下面的代码中给出了上述错误,但是如果我从 co.?
中删除 ?
它工作正常。
我试图关注 this MSDN example他们在哪里使用 ?
在线 select new { person.FirstName, PetName = subpet?.Name ?? String.Empty };
所以,看来我需要了解何时将 ?
与 ??
一起使用,何时不使用。
错误:
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 表达式被转换为委托(delegate)...而您使用的是 EF 或类似的 IQueryable<T>
查询,其中 lambda 表达式被转换为表达式树。表达式树不支持 null 条件运算符(或元组)。
按照老方法做:
price = co == null ? 0 : (co.price ?? 0)
(我相信 null 合并运算符在表达式树中没问题。)
关于c# - 表达式树 lambda 不能包含空传播运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44681362/