Home > Back-end >  .Net 4.6.1 application using Entity Framework 4.6.1 throws Null Exception using ToList(). The object
.Net 4.6.1 application using Entity Framework 4.6.1 throws Null Exception using ToList(). The object

Time:03-02

We have an application which is causing a null exception when we do a ToList(). We use Entity Framework 6 with c# and .Net 4.6.1.

The variable names were renamed to be generic. My apology if I caused any inconsistency in the syntax. It has worked for a long time and I have just seen this issue with it. Code is shown below:

var mYOrdList = new List<Order>();

mYOrdList.Add(order);
var mYOrdQuery = mYOrdList.AsQueryable<Order>();

The chained statement below includes the ToList(), which throws the null exception.Please note that the return value of .ToOrderDetail() is not a null!

var orderDetailViewModel = mYOrderQry.ToOrderDetail().ToList().First();
             

This snippet below shows the beginning of the ToOrderDetail():

public static IQueryable<OrderDetailViewModel> ToOrderDetail(
        this IQueryable<Order> orders)
    {
        return orders.Select(order => new OrderDetailViewModel
    {
    orderId = order.orderID,
    ...

I noticed that when looking at the data in the "order" object in the watch, some of the collections within this object were not visible and showed an "X". The related message was- "The metadata for EntityFrameworkDynamic Proxies - OurDataLayer is invalid. If you are doing a minidump, you may be able to fix this problem by collecting a new minidump with heap and evaluating the expressiion again."

I did not find a minidump in my c:\windows\minidump folder. That corresponds to my %systemroot% directory.

Can someone please advise?

Thank you, Ken

CodePudding user response:

ToOrderDetail returns IQueryable, so of course it isn't #null. The issue is that ToList will attempt to execute the IQueryable which is where your problem lies. The Null Reference exception will likely be that your code that is querying the Order to populate the DTO is attempting to reference a related navigation property that has not been eager loaded. This can appear to occur inconsistently because of the way EF will populate references with tracked entities even without an eager load call being made. If the DbContext was already tracking the related instances in questions for one Order, the call will work, but if you load another order where one or more references aren't already tracked and weren't eager loaded, then you get a Null Reference if lazy loading isn't enabled/available. These bugs tend to manifest when a DTO changes and someone just references a navigation property without checking that the property was eager loaded in all cases where that method is called.

Start by running mYOrderQry.ToList() and looking for null navigation properties that would be referenced by your DTO Select statement. To fix it, you need to ensure that these references are eager loaded.

  • Related