Search code examples
c#linqasp.net-core-2.2

LINQ query works in LINQPad but in C#


Below LINQ query works as expected in LINQPad but when I use this in Web API, it returns Nullable object must have a value exception.

Here is my code.

        var GRStk = (from g in GRStkB4
              join t1 in opTOs on g.itemCode equals t1.itemCode into temp1
              from op in temp1.DefaultIfEmpty()
              select new
              {
                   g.branchCode,
                   g.itemCode,
                   qty = g.availQty - op.opqty
               }).AsEnumerable().Where(w => w.qty > 0); // exception

       int ii = GRStk.Count(); // Exception with Nullable object must have a value.

I use Asp.Net Core 2.2 I could not understand how it works in LINQPad and what is nullable here?


Solution

  • Some commands in your query being evaluated in the client side when using EF, but not in linqPad. i.e if op is null then you may not be able to access op.opqty if it is evaluated in the client-side.

    I guess changing the following line will solve your problem tho:

    ...
                            select new
                  {
                       g.branchCode,
                       g.itemCode,
                       qty = g.availQty - (op!= null ?  op.opqty : 0) //edit here!
                   }).AsEnumerable().Where(w => w.qty > 0); // exception exception
    ...