1

I am creating a many to many-to-many relationship between the entities Invoice and Product as a hobby.
In my InvoiceProductController, I am trying to create an InvoiceProduct,but in the middle of creating of an invoiceProduct, for some reason the Product QtyOnHand did not decrease when I clicked on the create button.

I got an error when I ran the program, saying that Object reference not set to an instance of an object.

I have the evidence right here, in my InvoiceProductsController:

Product pro = db.InvoiceProducts.Find(invoiceProduct.Product).Product;
            pro.QtyOnHand -= invoiceProduct.QtyOrd;

After putting it after I created the InvoiceProduct, I still got the error. It still reads object not set to an instance of an object.

  • 4
    Either `db` or `invoiceProduct` is null, or the result of `Find()` is null. Use your debugger. –  Sep 29 '17 at 18:43

1 Answers1

0

Could this be caused by Lazy Loading?

If that's the case, the code below should work.

var pro = db.InvoiceProducts
             .Include("Product") //explicitly loading Product
             //for below: possibly x.Product.ID == invoiceProduct.Product.ID ?
             .Where(x=>x.Product == invoiceProduct.Product) 
             .FirstOrDefault().Product;
pro.QtyOnHand -= invoiceProduct.QtyOrd;
farzaaaan
  • 410
  • 3
  • 9
  • FirstOrDefault() requires a parameter. – Alfred Tsang Sep 29 '17 at 21:20
  • Is it asking you to pass a parameter in? I've never had to pass in a parameter in. What type of parameter is it asking for? – farzaaaan Sep 29 '17 at 21:25
  • It's a linq query – Alfred Tsang Sep 30 '17 at 01:20
  • Sorry I'm confused, FirstOrDefault() doesn't require any parameter. I think you are facing a different issue. Please see this link for FirstOrDefault(): https://msdn.microsoft.com/en-us/library/bb340482(v=vs.110).aspx – farzaaaan Sep 30 '17 at 01:25
  • For some reason, pro is null. I used my debugger to locate this. I read the link and found out that firstOrdefault does not require a parameter. Here is the evidence that caused this output: – Alfred Tsang Sep 30 '17 at 11:45
  • var pro = db.InvoiceProducts .Include("Product") //explicitly loading Product //for below: possibly x.Product.ID == invoiceProduct.Product.ID ? .Where(x => x.Product == invoiceProduct.Product) .FirstOrDefault().Product; – Alfred Tsang Sep 30 '17 at 11:50
  • In the .Where() clause try removing x.Prduct == invoiceProduct.Product with a more specific property. For example: x.Product.Name == invoiceProduct.Product.Name ( or use ID instead of Name, whichever property of Product you are using, make sure that it exists and has value in the InvoiceProduct.Product. ) – farzaaaan Sep 30 '17 at 13:51