【问题标题】:Why does a joined LINQ-to-SQL query generate a NullReferenceException?为什么连接的 LINQ-to-SQL 查询会生成 NullReferenceException?
【发布时间】:2019-10-28 21:20:14
【问题描述】:

我的数据库中有一个Document 表和一个Tenant 表,还有一个Document_Tenant 表将这两者关联起来。我正在尝试选择所有Documents,以及相关的Tenants,如果有的话。那应该是Document和Document_Tenant之间的左连接和Document_Tenant和Tenant之间的内连接,所以我跟着Entity framework left join得到了这个代码:

var combinedQuery = from doc in DocumentProvider.GetDocuments()
                    join dt in CustomTableItemProvider.GetItems<Document_TenantItem>()
                         on doc.ItemID equals dt.Document_ID into ddt
                    from x in ddt.DefaultIfEmpty()
                    join t in TenantProvider.GetTenants()
                         on x.Tenant_ID equals t.ItemID    // joined tenants
                    select new { doc, t.Tenant_ID };

但是,当该查询执行时,我得到了 NullReferenceException。我不知道为什么。

异常类型:NullReferenceException
异常消息:对象引用未设置为对象的实例。

在 lambda_method(Closure , f__AnonymousType372 , &lt;&gt;f__AnonymousType362 )
在 System.Linq.Enumerable.d__233.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator
2.MoveNext()
在 System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext()
at System.Linq.Enumerable.Count[TSource](IEnumerable
1 来源)

【问题讨论】:

  • 为什么不使用导航属性呢?为什么你要从不同的地方而不是从同一个上下文中获取相关表?

标签: c# linq-to-sql


【解决方案1】:

我在原来的帖子中犯了几个错误。一个是这实际上不是实体框架,而是一个与之类似的 API。这意味着我不能使用 Steve Py 建议的导航属性。

另外,这是关键,我过度简化了我的代码。在我发布select new { doc, t } 的地方,我抛出异常的代码是select new { doc, t.Tenant_ID }。由于这是左连接,t 值有时为 null - 这会导致 NullReference 异常。

我将选择更改为阅读:

select new {
    Doc = doc,
    Tenant_ID = t == null ? null : t.Tenant_ID
};

旁注:我不确定为什么我们不能在选择中使用空合并运算符,但我们不能。

【讨论】:

  • 我在单元测试方法中遇到了同样的问题。测试方法有效,但测试未通过并引发与您的相同的异常。您的解决方案有所帮助。感谢您分享这个有趣的场景。
猜你喜欢
  • 1970-01-01
  • 2011-09-20
  • 2011-03-19
  • 2017-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多