LINQ查询抛出Null引用异常

问题描述 投票:0回答:4

我正在使用LINQ查询来填充数据网格。作为新增强功能的一部分,我必须通过在WHERE子句中包含一个以上的条件来更改现有的LINQ查询。看了这么多帖子,感觉堆叠WHERE子句条件很简单。之前的查询返回简单的对象类型(匿名)并且工作正常。现在我将查询分为两部分。在第一部分中,我试图返回已知类型并尝试在下一部分中堆叠where子句。但有些人如何不工作而不取任何结果。它在grid上抛出NULL引用异常.DataBind抛出异常(Null引用异常。)在这里发布我的代码。

Using db As New ProjectDataContext
        Dim orderLines As IEnumerable(Of orderline)
        Dim customOrderLines As Object
        Try
            If VATSearch = 1 Then
                ' Show only VAT orders
                'orderlines = (From O In db.orderlines Where O.order.order_date > MinTime And O.order.order_date < MaxTime And O.order.order_status_fk > 1 And (O.ol_vat_free Is Nothing OrElse O.ol_vat_free = 0) Order By O.order.order_date _
                '        Select OrderLineID = O.ol_id, Ref = O.order.order_ref, Email = CStr(IIf(O.order.User Is Nothing, O.order.order_billing_email, O.order.User.user_email)), Code = O.StockItem.productsbycolor.product.product_code & O.StockItem.productsbycolor.color.color_code, Size = O.size.size_code, Qty = O.ol_qty, Price = O.ol_product_price, LineTotal = O.ol_lineprice, Delivery = (O.order.order_delivery_total / O.order.orderlines.Count), NonVAT = O.order.order_vat_free _
                '            )
                orderLines = (From o In db.orderlines Where o.order.order_date > MinTime And o.order.order_date < MaxTime And o.order.order_status_fk > 1 And (o.ol_vat_free Is Nothing OrElse o.ol_vat_free = 0) Order By o.order.order_date _
                Select o)


            ElseIf VATSearch = 2 Then
                ' Show only non-VAT orders
                'orderlines = (From O In db.orderlines Where O.order.order_date > MinTime And O.order.order_date < MaxTime And O.order.order_status_fk > 1 And (Not O.ol_vat_free Is Nothing) AndAlso O.ol_vat_free = 1 Order By O.order.order_date _
                '    Select OrderLineID = O.ol_id, Ref = O.order.order_ref, Email = CStr(IIf(O.order.User Is Nothing, O.order.order_billing_email, O.order.User.user_email)), Code = O.StockItem.productsbycolor.product.product_code & O.StockItem.productsbycolor.color.color_code, Size = O.size.size_code, Qty = O.ol_qty, Price = O.ol_product_price, LineTotal = O.ol_lineprice, Delivery = (O.order.order_delivery_total / O.order.orderlines.Count), NonVAT = O.order.order_vat_free _
                '                )
                orderLines = (From O In db.orderlines Where O.order.order_date > MinTime And O.order.order_date < MaxTime And O.order.order_status_fk > 1 And (Not O.ol_vat_free Is Nothing) AndAlso O.ol_vat_free = 1 Order By O.order.order_date _
                        Select O)
            Else
                ' Show both VAT and non-VAT orders
                'orderlines = (From O In db.orderlines Where O.order.order_date > MinTime And O.order.order_date < MaxTime And O.order.order_status_fk > 1 Order By O.order.order_date _
                '   Select OrderLineID = O.ol_id, Ref = O.order.order_ref, Email = CStr(IIf(O.order.User Is Nothing, O.order.order_billing_email, O.order.User.user_email)), Code = O.StockItem.productsbycolor.product.product_code & O.StockItem.productsbycolor.color.color_code, Size = O.size.size_code, Qty = O.ol_qty, Price = O.ol_product_price, LineTotal = O.ol_lineprice, Delivery = (O.order.order_delivery_total / O.order.orderlines.Count), NonVAT = O.order.order_vat_free _
                '            )
                orderLines = (From o In db.orderlines Where o.order.order_date > MinTime And o.order.order_date < MaxTime And o.order.order_status_fk > 1 Order By o.order.order_date _
                        Select o)
            End If

            customOrderLines = (From o In orderLines
                        Select orderLineID = o.ol_id, ref = o.order.order_ref, email = CStr(IIf(o.order.User Is Nothing, o.order.order_billing_email, o.order.User.user_email)),
                        code = o.StockItem.productsbycolor.product.product_code & o.StockItem.productsbycolor.color.color_code,
                        size = o.size.size_code, qty = o.ol_qty, price = o.ol_product_price, lineTotal = o.ol_lineprice,
                        delivery = (o.order.order_delivery_total / o.order.orderlines.Count), nonVAT = o.order.order_vat_free, orderPaymentType = o.order.order_google_order_number)

            results.DataSource = customOrderLines
            results.DataBind()
            results.Visible = True
            btnExportButton.Visible = True

        Catch ex As Exception

        End Try
    End Using
c# vb.net linq entity-framework linq-to-sql
4个回答
0
投票

在select之后使用new来创建匿名类型并将其括在大括号中。

customOrderLines = (From o In orderLines
                    Select new { orderLineID = o.ol_id, ref = o.order.order_ref, email = CStr(IIf(o.order.User Is Nothing, o.order.order_billing_email, o.order.User.user_email)),
                    code = o.StockItem.productsbycolor.product.product_code & o.StockItem.productsbycolor.color.color_code,
                    size = o.size.size_code, qty = o.ol_qty, price = o.ol_product_price, lineTotal = o.ol_lineprice,
                    delivery = (o.order.order_delivery_total / o.order.orderlines.Count), nonVAT = o.order.order_vat_free, orderPaymentType = o.order.order_google_order_number})

我希望这将有所帮助。


0
投票

我收到错误,因为我使用IIF进行空检查。

有时它返回null并且查询抛出NULL引用异常。

现在我使用IF而不是IIF,它工作正常。

  • 纳雷什

0
投票

您得到的错误表明您尝试运行的LINQ没有返回任何值,因此customOrderLines将作为空集合返回。由于LINQ包含相当多的过滤器,我建议删除Dim customOrderLines As Object,而是做类似的事情:

Dim customOrderLines = (From o In orderLines 
  Select orderLineID = o.ol_id, ref = o.order.order_ref, 
  email = CStr(IIf(o.order.User Is Nothing, o.order.order_billing_email, o.order.User.user_email)), 
  code = o.StockItem.productsbycolor.product.product_code & o.StockItem.productsbycolor.color.color_code, 
  size = o.size.size_code, qty = o.ol_qty, price = o.ol_product_price, lineTotal = o.ol_lineprice, 
  delivery = (o.order.order_delivery_total / o.order.orderlines.Count), nonVAT = o.order.order_vat_free, 
  orderPaymentType = o.order.order_google_order_number)

if customOrderLines isnot nothing andalso customOrderLines.Any then
  results.DataSource = customOrderLines 
  results.DataBind() 
  results.Visible = True 
  btnExportButton.Visible = True
else
  results.DataSource = nothing
  results.DataBind()
  results.Visible = False
  btnExportButton.Visible = False
end if

这将确保您不会尝试绑定空集合,如果datagrid没有返回任何内容,它也会清除您的LINQ

但主要的问题仍然是你的LINQ正沿着这条线返回一个空集合。我主要建议回去并确保LINQ实际上使用LINQpad或类似的其他实用程序带回您的期望。

你可以得到LinqPad Here


0
投票

我在这个页面上,因为我得到了一个NullReferenceException

var allHeights = MyCities.SelectMany(city => 
    city.Houses.SelectMany(h => 
        h.Storeys.Values.Select(s => new { City = city, House = h, Storey = s })))
   .GroupBy(g => g.Storey.Height)
   .OrderBy(heightGroup => heightGroup.Key)
   .ToList();
int i = 0;
foreach (var heightGroup in allHeights)
{
    if (i > 1)
    {
        var previousHeightGroup = allHeights[i-1].ToList();
        var previousPartIDs = previousHeightGroup.Select(g => g?.City?.Name).ToList();
        //.... <do stuff in case of i > 0>
    }
    // do other stuff
    i++;
}

previousHeightGroup.Select(g => g?.City?.Name).ToList()”扔了一个NullReferenceException,尽管:

  • 此数据结构的所有元素均不为null
  • previousHeightGroup不是空的
  • “Name”是City对象上的字符串属性,并且是非空的
  • Values对象上的Storeys集合是非空的
  • 无论如何,在NullReferenceException时,allHeights列表应该由ToList()调用完全评估,并且Values解决
  • 显然,所有偶然的空成员访问都受到Elvis运算符的保护,即使访问的成员实际上不是null

而且,我重构了这样的代码:

.Select(g => {
   var group = g;
   var city = g?.City;
   var cityName = city?.Name;
   return cityName;
})

...即,我在Select中解析引入的数据结构,并在调试器中单步执行它,一切正常。然而,Select()电话当时有一个NullReferenceException,据称在我自己的代码中。

解决这个问题的唯一方法是稍微重构代码,关闭Visual Studio(2017)和整个机器,重启所有内容,错误不再重现。

这意味着,LINQ有时会在这里和那里呕吐。

这是.Net 4.6.1。

© www.soinside.com 2019 - 2024. All rights reserved.