7

i am getting an error that says 'Non Static Method requires a target'

Here is the code that is causing me the error, could anyone possible shed some light on this?

//TODO: Error, Non static method requires a target.
var orderItem =
    _context.PurchaseOrderItems.FirstOrDefault(
        p => p.JobReference == item.JobReference && p.ItemNumber == item.ItemNumber);
return _context.DeliverySchedules.Include(d => d.PurchaseOrderItem)
           .Where(d => d.PurchaseOrderItem.Id == orderItem.Id)
               .ToList();
Shahzad
  • 1,315
  • 2
  • 22
  • 42
Corey James Carney
  • 167
  • 1
  • 2
  • 14
  • An exception of type 'System.Reflection.TargetException' occurred in EntityFramework.SqlServer.dll but was not handled in user code Additional information: Non-static method requires a target. – Corey James Carney May 08 '17 at 08:11
  • Have a look here: http://stackoverflow.com/questions/13717355/non-static-method-requires-a-target. – Wouter van Vegchel May 08 '17 at 08:11
  • 1
    `.Where(d => d.PurchaseOrderItem.Id == orderItem.Id)` may throwing NRE if `orderItem` has null or no results returned from first query. Try testing null condition before returning another query using `if (orderItem != null)`. – Tetsuya Yamamoto May 08 '17 at 08:13
  • Change the `FirstOrDefault` to `Single` because in the next line you will get to its properties and you dont want a NullReferenceException. – Cleptus May 08 '17 at 08:15

2 Answers2

7

The FirstOrDefault method may return null value if no query results returned there:

var orderItem = _context.PurchaseOrderItems.FirstOrDefault(
                p => p.JobReference == item.JobReference && p.ItemNumber == item.ItemNumber);

Since orderItem.Id throws NullReferenceException when orderItem is null, it will propagate to LINQ throwing TargetException as mentioned in question (see this post and this post for more info).

Hence, you need to check presence of null value from orderItem by modifying second LINQ query to this one:

return _context.DeliverySchedules.Include(d => d.PurchaseOrderItem)
       .Where(d => (orderItem != null && d.PurchaseOrderItem.Id == orderItem.Id))
       .ToList();

NB: Null checking must takes place before retrieving property Id of orderItem to prevent NullReferenceException.

As an alternative, if condition to check against null value may be used without modifying second query:

if (orderItem != null)
{
    return _context.DeliverySchedules.Include(d => d.PurchaseOrderItem)
           .Where(d => d.PurchaseOrderItem.Id == orderItem.Id)
           .ToList();
}
Community
  • 1
  • 1
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
0

Change the FirstOrDefault to Single because in the next line you will get to its properties and you dont want a NullReferenceException

Cleptus
  • 3,446
  • 4
  • 28
  • 34