【问题标题】:C# anonymous type warning when Nullable Reference Types is enable启用可空引用类型时的 C# 匿名类型警告
【发布时间】:2022-01-23 07:13:40
【问题描述】:

我正在使用启用了 Nullable Reference Type 的 .net 6,当我使用匿名类型来获取 LINQ 查询的结果时,我收到警告 Client is not null here。 CS8619:类型 的值中的引用类型为空性与类型

这是我的代码:

 var contracts = _dbContext.Contracts.Select(
                    c => new
                    {
                        c.ContractId,
                        c.Client.Name,
                        c.Client.Street
                    }
                ).Where(c => c.ContractId == contractId).Take(9).ToList();

进行查询和避免警告的正确方法是什么?

【问题讨论】:

  • 能否请您发布完整的代码和错误?
  • 我不认为这可以编译,是吗?您在 .Where 之前缺少右括号。此外,您的 Where 过滤器对未选择的属性进行了过滤。
  • 是的,对不起,让我编辑代码,并添加完整的错误。
  • 看来这与Client的模型中street可以为null有关,请问如何在查询中指出匿名类型生成的street可以为null?跨度>

标签: c# .net-6.0 nullable-reference-types


【解决方案1】:

试试这个:

var contracts = _dbContext.Contracts
             .Include(x => x.Client) // Include clients
             .Where(c => c.ContractId == contractId)
             .Select(c => new
             {
                 c.ContractId,
                 Name = c.Client == null ? null : c.Client.Name, // nullable check and line up namings of properties 
                 Street = c.Client == null ? null : c.Client.Street // nullable
             })
            .Take(9)
            .ToList();

如果ClientId[Required],看起来Client不可能是null,唯一缺少的可能是子查询.Include(x => x.Client)

【讨论】:

  • 谢谢冬冬,我尝试应用你的建议,但出现错误,表达式树 lambda 可能不包含空传播运算符。
  • @LuisZenteno 已更新。这篇文章可以提供帮助:stackoverflow.com/questions/44681362/…
猜你喜欢
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多