表达式树 lambda 不能包含空传播运算符 [英] An expression tree lambda may not contain a null propagating operator

查看:126
本文介绍了表达式树 lambda 不能包含空传播运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

price = co?.price ??0, 在下面的代码中给了我上面的错误,但是如果我从 co.? 中删除 ? 它工作正常.

The line price = co?.price ?? 0, in the following code gives me the above error, but if I remove ? from co.? it works fine.

我试图关注 这个 MSDN示例 他们使用 ? 在线 select new { person.FirstName, PetName = subpet?.Name ??String.Empty }; 所以,看来我需要了解什么时候用 ??? ,什么时候不用.

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 表达式被转换为 委托...而您使用的是 EF 或类似的,带有 IQueryable 查询,其中 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)

(我相信空合并运算符在表达式树中很好.)

(I believe the null-coalescing operator is fine in an expression tree.)

这篇关于表达式树 lambda 不能包含空传播运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆