【问题标题】:Check for null before referencing joining table fails在引用连接表失败之前检查 null
【发布时间】:2021-07-06 05:42:13
【问题描述】:

我有一个User 表,它可能在Address 中有相关(FK)记录。

所以在LINQ,我正在尝试:

var data = _context.User.Where(x=>x.Deleted.HasValue == false)
  .Select(y=> new MyObject {
      Id = y.Id,
      Name = y.Name,
      Address = y.Address != null ? y.Address.Description : null
  });

但是一旦我添加了三元运算符(因为如果那里没有记录,我无法引用 y.Address.Description),我的 Select 就会失败并出现设计时错误:Ambiguous Invocation

这样做的正确方法是什么?在这种情况下,可能没有“地址”记录。

“选择”上的设计时错误:

【问题讨论】:

  • 粘贴“实际”异常和堆栈跟踪
  • '设计时错误:不明确的调用。' --- 你的意思是编译时错误?
  • 没有。设计时间。在我编译之前,UI 就显示了这一点,只要我添加了 turnary。
  • 其中的 ui,我很勇敢。 linq 是否依赖于某些 ui?
  • 我使用 Rider。问题似乎是根据接受的答案需要强制转换。

标签: c# entity-framework linq


【解决方案1】:

我认为您需要将 null 转换为字符串:

var data = _context.User.Where(x=>x.Deleted.HasValue == false)
  .Select(y=> new MyObject {
      Id = y.Id,
      Name = y.Name,
      Address = y.Address != null ? y.Address.Description : (string) null
  });

我在这里假设 Description 是字符串类型。

您也可以尝试 Null 条件运算符:

var data = _context.User.Where(x=>x.Deleted.HasValue == false)
  .Select(y=> new MyObject {
      Id = y.Id,
      Name = y.Name,
      Address = y.Address?.Description
  });

问题与类型推断有关。编译器无法确定三元运算符的结果类型,因此需要通过强制转换显式指示第三个操作数(null)的类型。

查看相关问题:Understanding C# compilation error with ternary operator

导致此错误的简单示例:

int? i = true ? 1 : null;

在 Visual Studio 2019 / .Net Framework 4.7.2 上,我收到以下错误:

Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'

更正:

int? i = true ? 1 : (int?) null;

【讨论】:

  • 哇!谢谢!这就对了。我不知道为什么会这样。但它奏效了。
  • @Tarik,除了解决问题,你能解释一下为什么会出错,并提供最少的代码来解决这个错误(可能与 linq 无关)吗?
  • @LeiYang 补充说明
  • 您能否在简单的 c# 控制台应用程序中提供导致Ambiguous Invocation 异常的最少代码
  • @LeiYang 按照建议添加了一个示例。
猜你喜欢
  • 1970-01-01
  • 2017-05-12
  • 2010-10-07
  • 1970-01-01
  • 2010-12-27
  • 1970-01-01
  • 2015-05-30
  • 2018-06-13
  • 2011-01-12
相关资源
最近更新 更多