c# - 表达式树 lambda 不能包含空传播运算符

标签 c# linq null-coalescing-operator null-propagation-operator

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/

相关文章:

c# - 我可以在 Linq 查询中选择多个对象吗

templates - Play 2.x 空安全合并(避免模板中的 NPE)

c# - 是否可以在 C# 中合并字符串和 DBNull?

c# - 有没有办法实现和使用 "NOT null coalescing"运算符?

c# - 你能传递一个类型并强制在 C# 中传递什么类型吗?

c# - MVC3 将字典<string,bool> 从 View 传递到 Controller

类型 Dictionary<string,string> 不支持 C# 比较运算符

c# - 确定 null 或计数 0 的最佳方法

c# - 如何在 RichTextBox [C#] 中进行语法高亮显示?

c# - 如何以简单的方式搭建数据库表?