Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to do an if/else. I need to first check the database order_details table to see if the quantity is zero. If greater than zero go to submission page else go to home page.


This is what I have.


C#
public ActionResult Patients()
       {
            //query database for userId RoleId and Purchase product.
            var query = (from u in db.aspnet_Users
                         where u.UserName == User.Identity.Name
                         join d in db.Doctors on u.UserId equals d.UserId
                         join o in db.OrderDetails on d.DoctorsId equals o.DoctorsId
                         select o).FirstOrDefault().Quantity;
            //check against the quantity table for valid purchase.
            if (query > 0)

            {
                 return View();
            }
            else
            {
                 return RedirectToAction("Index", "Home");
            }
       }


If the Order Details quantity column is zero it crashes.
Any one I Log on with that has a number in the quantity column in my database it works.

I hope I am explaining this right. To go to the patients submit page when a user clicks on the tab it need to query the database to check to see if purchase services.
Posted
Comments
Sergey Alexandrovich Kryukov 20-Mar-12 18:51pm    
"It crashed" is not informative. You could get complete exception information, indicate in what line of code exactly, etc. Did you gather this information?
--SA

1 solution

The FirstOrDefault method returns null, if there is no item.


You have to check the value that is returned from from the FirstOrDefault method, before using it. Something like the following:


C#
var orderDetail = (from u in db.aspnet_Users
            where u.UserName == User.Identity.Name
            join d in db.Doctors on u.UserId equals d.UserId
            join o in db.OrderDetails on d.DoctorsId equals o.DoctorsId
            select o).FirstOrDefault();

var query = (orderDetail != null) ? orderDetail.Quantity : 0;
 
Share this answer
 
Comments
postonoh 21-Mar-12 9:22am    
Thanks will try.
postonoh 21-Mar-12 9:27am    
Shmuel Zang you are one of the reason I joined the site. Thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900