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.
LVL 1
Moti Mashiah.NET DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

it_saigeDeveloperCommented:
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 -Capture.JPG-saige-
0
Moti Mashiah.NET DeveloperAuthor Commented:
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

0
Moti Mashiah.NET DeveloperAuthor Commented:
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.
0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Moti Mashiah.NET DeveloperAuthor Commented:
I'm not allow to change is I meant.
0
it_saigeDeveloperCommented:
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-
0
Moti Mashiah.NET DeveloperAuthor Commented:
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
0
Moti Mashiah.NET DeveloperAuthor Commented:
Please, see attachment. This is the table I query from.


Capture.PNG
0
it_saigeDeveloperCommented:
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-
0
Moti Mashiah.NET DeveloperAuthor Commented:
Same Issue.

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

For Example -When I put my mouse over 'var o' in the foreach (var o in tOrders) line, I get the following from intellisense.-saige-
0
Moti Mashiah.NET DeveloperAuthor Commented:
decimal supplierList cost
0
it_saigeDeveloperCommented:
Could you perhaps provide a screenshot?  And to verify this does intellisense indicate that supc is an anonymous type?

-saige-
1
Moti Mashiah.NET DeveloperAuthor Commented:
Hi There,

Thank you for your help, the supc is anonymous type and here ismy solution:

 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 && supc.Cost > 0)
                {
                    objItem.Cost = supc.Cost;
                }
                else
                {
                    objItem.Cost = item.Cost;
                }

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

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
it_saigeDeveloperCommented:
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-
0
Moti Mashiah.NET DeveloperAuthor Commented:
Thank you very much for explanation.
0
Moti Mashiah.NET DeveloperAuthor Commented:
Solved
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.