1

I couldn't understand what was happening when I use Linq.Any() method to check if object contains a specific value, the code throws a NullReferenceException on variable with data prior it's use.

The code below:

        public ML.Order FetchOrder(ML.MLDBContext db, long OrderID)
        {
            if (db == null)
                db = new ML.MLDBContext();            

           //avoided code to fetch the Order details from another system via API

            Order apiOrder = api.OrdersGet(OrderID);

            //avoided code to test null results

            bool isNew = false; //to check if fetched order is new or must be updated on DB

            //load from DB
            ML.Order dbOrder = db.Orders.Where(o => o.OrderID == apiOrder.id).FirstOrDefault();
            if (dbOrder == null)
            {
                isNew = true;

                //avoided code to fill dbOrder with apiOrder data

                //Below code check if user bought the same product before

                //the error is thrown here but it's not null
                string ListingID = apiOrder.order_items.First().item.id; 
                var previousOrders = db.Orders.Where(order => order.OrderID != apiOrder.id && order.CustomerID == apiOrder.buyer.id && order.SellerID == apiOrder.seller.id).ToList();

                foreach (ML.Order prevOrder in previousOrders)
                {
                    if (prevOrder.OrderedItems.Any(i => i.ListingID == ListingID)) //Line who causes the error
                    {
                          //code to mask as reordered item
                    }
                }

Some points:

I'm sure "apiOrder.order_items.First().item.id" always have any value.

I'm sure the Order contains the item I'm looking for and the field isn't nullable.

When I comment the line who causes the error, the debug will pass through without errors

To solve this problem, I had to replace Linq.Any() by foreach

        foreach (ML.Order prevOrder in previousOrders)
        {
            foreach (ML.OrderedItem item in prevOrder.OrderedItems)
            {
                if (item.ListingID == ListingID)
                {
                     //code to mask as reordered item
                }
            }

        }

My doubt is: Does Linq.Any() or EntityFramework Monitor variables prior to it's declaration and use?

Why the NullreferenceException was trowed on variable prior it usage?

What's the problem using the Linq.Any() method to check the existence of a value inside EF object?

Diego Mendes
  • 10,631
  • 2
  • 32
  • 36
  • 2
    What happens when `prevOrder.OrderedItems` is null? Your exception happens... so it should be `if ((prevOrder.OrderedItems != null) && (prevOrder.OrderedItems.Any(i => ....` – entropic Nov 21 '14 at 22:22
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – crthompson Nov 21 '14 at 22:24
  • @entropic prevOrder.OrderedItems will never be null, I only create an Order with Itens and in this case the OrderedItems isn't null or empty, it's value count is always 1 – Diego Mendes Nov 21 '14 at 22:25
  • @paqogomez isn't the same problem, I checked this before – Diego Mendes Nov 21 '14 at 22:26
  • Null reference is ALWAYS the same thing. You are trying to access the property of a variable whose value is null. Step through your code. I think you'll find that @entropic is right on the money. Either `prevOrder` or `OrderItems` is null. – crthompson Nov 21 '14 at 22:31
  • @DiegoMendes you may THINK it will never be null, but you don't actually know that is the case. Step through the code with the debugger, and I believe you'll be pretty surprised when `OrderedItems` turns out to be null. It won't be `prevOrder` in this case, because you're looping through an iterator with the `foreach` – entropic Nov 21 '14 at 22:37
  • @entropic I did that, as I cleared on my Question, I'm sure the OrderedItens isn't null. I debugged the code at least 20 times to understand what was happening, all values was there, nothing null, as I said before, the problem isn't with OrderedItems content, but .Any() method. As I described before, if I exchange the .Any() by Foreach, everything works fine. My doubt is: Why? if everything is okay. – Diego Mendes Nov 21 '14 at 22:45
  • @paqogomez I know what's NullRefereneExceptiom, I'm sure its not null null values, I debugged the code to find the problem, and the problem is .Any() method, as said on my previous comment. if OrderedItems was null, the code doesn't step inside foreach. as my POST The error doens't occur on OrderedItems, but occurs because of that line, at a variable declared before of it's execution. – Diego Mendes Nov 21 '14 at 22:47
  • then `i` from `i.ListingID` is null. – crthompson Nov 21 '14 at 22:51
  • @paqogomez isn't. I checked OrderedItem contains 1 iten, i.ListingId isn't nullable and isn't null – Diego Mendes Nov 21 '14 at 22:53
  • I lost at least 2 hours to find the problem, I checked every variable and value. The code are working with foreach, but doesn't work with .Any() – Diego Mendes Nov 21 '14 at 22:55
  • Ok.. well.. perhaps you can make a [fiddle](http://dotnetfiddle.com) to prove your point. I am SURE the problem is not `Any`, but rather your data. – crthompson Nov 21 '14 at 22:55
  • I was sure the problems wasn't .Any() and I still can't understand why it throws an exception on a variable before its usage. May you didn't notice, but the line where error occurs is "string ListingID = apiOrder.order_items.First().item.id;" but this error occurs only if I use .Any() few lines below. Is a strange error – Diego Mendes Nov 21 '14 at 23:00
  • I think the problem isn't exactly with .Any() but anything related to EntityFramework – Diego Mendes Nov 21 '14 at 23:11
  • 1
    Your notes say that the error occurs on the `if` line!?!?! So, here we go again. Is `apiOrder` null? Is `order_items` null? Is `First().Item` null? Does `ListingID` come back null? ONE of those is null. Its NOT EF and its NOT `Any()` – crthompson Nov 21 '14 at 23:24
  • Let me explain again: if I use .Any() I'll use the ListingID variable to compare, and ListingID line is where the error occurs. if I remove the if line where is .Any() the code pass. ListingID isn't null, none of these variables are null. Another point: I had to add a filter by date for last 30 days, "DateTimeOffset dateLimit = DateTimeOffset.Now.AddDays(-30)" when I add dateLimit to db.Orders.Where(), the nullreferenceexception is thrown on dateLimit, as you can see, dateLimit use DateTimeOffset.Now to fill and NullReferenceException can't happen there. – Diego Mendes Nov 21 '14 at 23:34
  • if I create the variables and don't pass as parameter to query of EF the error doesn't throw. is a very strange error, I'm sure is there anything related to EF, I can't understand what. – Diego Mendes Nov 21 '14 at 23:35

0 Answers0