Mikael Edebro
Mikael Edebro

Reputation: 241

MVC 3 - How to know if query returns 0 rows

Probably pretty easy, but I can't get it sorted out. I want to redirect the user to an error page if the requested id doesn't exist in the database. My code:

public ActionResult Details(int id)
    {

        DetailsAdViewModel DAVM = new DetailsAdViewModel();
        DAVM.Ad = db.Ads.Include("Images").Where(a => a.AdId == id).First();
        DAVM.FirstImage = db.Images.Where(a => a.AdId == id).OrderBy(a => a.ImageId).Take(1);

        // make sure the ad isn't deleted or that it really exists
        if (DAVM.Ad == null)
        {
            return RedirectToAction("ShowError", "Error", new { errorCode = "adDeleted" });
        }

        return View(DAVM);
    }

This doesn't work, and there is an server error if I enter a false id.

Upvotes: 0

Views: 331

Answers (2)

Mikael Edebro
Mikael Edebro

Reputation: 241

Found a solution:

public ActionResult Details(int id) {

        if (db.Ads.Any(a => a.AdId == id))
        {
            DetailsAdViewModel DAVM = new DetailsAdViewModel();
            DAVM.Ad = db.Ads.Include("Images").Where(a => a.AdId == id).First();
            DAVM.FirstImage = db.Images.Where(a => a.AdId == id).OrderBy(a => a.ImageId).Take(1);

            return View(DAVM);
        }
        else
        {
            return RedirectToAction("ShowError", "Error", new { errorCode = "adDeleted" });
        }
    }

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039100

Use .FirstOrDefault() instead of .First(). This will return null if not record is found instead of throwing an exception:

DAVM.Ad = db.Ads.Include("Images").FirstOrDefault(a => a.AdId == id);

Now you can check if DAVM.Ad is null:

if (DAVM.Ad == null)
{
    return RedirectToAction("ShowError", "Error", new { errorCode = "adDeleted" });
}

Upvotes: 1

Related Questions