PriceCheaperton PriceCheaperton - 26 days ago 6
ASP.NET (C#) Question

Adding FirstOrDefault to my query?

How do i add first or default to my controller:

public ActionResult Index(string searchString)
{
var customers = from s in db.TicketDetails
select s;

if (!String.IsNullOrEmpty(searchString))
{
//search criteria
customers = customers.Where(s => s.SupportRef.Contains(searchString));
}
return View(db.TicketDetails.ToList());
}


I need to make sure my results only return 1 record. If they return
null
then I need to pass in dummy values.

Answer

Use the SignleOrDefault to make sure you have only one object. If you have more than one item then you will get null (as it is the default value of the object). If the result will be null then the ?? will make it intantiate the SomeDummyObject

return View(customers.SingleOrDefault() ?? new SomeDummyObject());

All together you can write it this way:

public ActionResult Index(string searchString)
{
    var defaultReturnValue = //you default dummy object

    if(String.IsNullOrEmpty(searchString))
        return View(defaultReturnValue);

    var customers = from s in db.TicketDetails
                    where s.SupportRef.Contains(searchingString)
                    select s;

    return View(customers.SingleOrDefault() ?? defaultReturnValue);
}

If you don't mind that the table contains more than one item matching the predicate but only want to get one value then replace SingleOrDefault with FirstOrDefault. More on the difference between the two see on SO Documentation

Comments