Link to home
Start Free TrialLog in
Avatar of Moti Mashiah
Moti MashiahFlag for Canada

asked on

C# asp.net mvc

HI Guys,

I have MVC 4 application and I have some  issue when decimal property return NULL from the database.

Here is my example:

var supc1 = (from u in _db.SupplierLists where u.ItemID == itm.ID && u.SupplierID == itm.SupplierID select new { u.Cost, u.ReorderNumber }).FirstOrDefault();

Open in new window



you can see in this code I query data from two columns - u.cost and u.reordernumber. my question is, when cost comes NULL how can I deal with this and let the code return 0 instead and prevent from the code the throw an exception.



Thanks.
Avatar of it_saige
it_saige
Flag of United States of America image

Probably something like:
var supc1 = (from u in _db.SupplierLists where u.ItemID == itm.ID && u.SupplierID == itm.SupplierID select new { Cost = (u.Cost != null) ? u.Cost : 0, u.ReorderNumber }).FirstOrDefault();

Open in new window


Proof of concept:
using System;
using System.Collections.Generic;
using System.Linq;

namespace EE_Q28694099
{
	class Program
	{
		static List<Supplier> Orders = new List<Supplier>();

		static void Main(string[] args)
		{
			for (int i = 0; i < 20; i++)
			{
				Supplier order = new Supplier() { ID = i, OrderNumber = i };
				if (i % 2 == 0)
					order.Cost = null;
				else
					order.Cost = i;

				Orders.Add(order);
			}

			var tOrders = (from o in Orders where o.ID % 5 == 0 select new { Cost = (o.Cost != null) ? o.Cost : 0, o.OrderNumber });
			foreach (var o in tOrders)
				Console.WriteLine("Cost: {0}; OrderNumber: {1}", o.Cost, o.OrderNumber);
			Console.ReadLine();
		}
	}

	class Supplier
	{
		public int ID { get; set; }
		public decimal? Cost { get; set; }
		public int OrderNumber { get; set; }
	}
}

Open in new window

Produces the following output -User generated image-saige-
Avatar of Moti Mashiah

ASKER

Thanks for the quick replay, but still getting an expetion

here is my full code:
var supc = (from u in _db.SupplierLists where u.ItemID == itm.ID && u.SupplierID == itm.SupplierID select new { Cost = (u.Cost != null) ? u.Cost : 0, u.ReorderNumber }).FirstOrDefault();

             

                if (supc.Cost != 0)
                {
                    objItem.Cost = supc.Cost;
                }
                else
                {
                    objItem.Cost = item.Cost;
                }

                if (supc.ReorderNumber != null || supc.ReorderNumber != "")
                {
                    objItem.Reordernumber = supc.ReorderNumber;
                }
                else
                {
                    objItem.Reordernumber = "";
                }

                objItem.QuantityOnOrder = item.QuantityOnOrder;
                objItem.Extcost = Convert.ToDecimal(Convert.ToDouble(item.Cost) * item.QuantityOnOrder);
                objItem.Subtotal = Convert.ToDecimal(Convert.ToDouble(item.Cost) * item.QuantityOnOrder);
                objItem.Total = Convert.ToDecimal(Convert.ToDouble(item.Cost) * item.QuantityOnOrder);
                objItems.Add(objItem);
                objItem.lstItems = objItems;
            }

            TempData["storeitms"] = objItem;

            return PartialView("_Listoforder", objItems

Open in new window

Actually in your properties the decimal is decimal? and mine show just decimal and I can't change it because it is the entity from the database.
I'm not allow to change is I meant.
I understand that.  My example was provided showing that I was making the cost property nullable.  Where exactly are you getting your exception?  And what is the exception.

-saige-
I'm getting the exception in the line -

if (supc.Cost != 0)
                {
                    objItem.Cost = supc.Cost;
                }
the message says - inneerException null  

BTW,
the cost field in my database is not nullable
Please, see attachment. This is the table I query from.


User generated image
Let's try a different tact:
var supc = (from u in _db.SupplierLists where u.ItemID == itm.ID && u.SupplierID == itm.SupplierID select new { Cost = (decimal?) u.Cost ?? 0, u.ReorderNumber }).FirstOrDefault();

Open in new window

-saige-
Same Issue.

Thank for your quick reply.
What does intellisense tell you about the Cost element of your anonymous type?

For Example -User generated image-saige-
decimal supplierList cost
SOLUTION
Avatar of it_saige
it_saige
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ah, I understand where the hangup was.  It was not that Cost was a null value, but your supc object was null (this is based on the usage of FirstOrDefault).  My mistake for not digging deeper.

So there are a couple of ways to resolve this (one you have already identified).  I would probably rewrite it as such though:
var supc = (from u in _db.SupplierLists where u.ItemID == itm.ID && u.SupplierID == itm.SupplierID select new { u.Cost,u.ReorderNumber}).FirstOrDefault();

if (supc == null)
	// Do something here to indicate that the order could not be found.
else
{
	objItem.Cost = (supc.Cost > 0) ? supc.Cost : item.Cost;
	objItem.Reordernumber = !string.IsNullOrEmpty(supc.ReorderNumber) ? supc.ReorderNumber : string.Empty;
}

Open in new window

The other solution is to use First instead and enclose in a try...catch block:
try
{
	var supc = (from u in _db.SupplierLists where u.ItemID == itm.ID && u.SupplierID == itm.SupplierID select new { u.Cost,u.ReorderNumber}).First();
	objItem.Cost = (supc.Cost > 0) ? supc.Cost : item.Cost;
	objItem.Reordernumber = !string.IsNullOrEmpty(supc.ReorderNumber) ? supc.ReorderNumber : string.Empty;
}
catch (Exception ex)
{
	// Do something here to indicate that the order could not be found.
}

Open in new window

-saige-
Thank you very much for explanation.
Solved