MVC 3 - 如何知道查询是否返回0行

时间:2012-09-20 10:44:12

标签: asp.net-mvc-3

可能很简单,但我无法理清它。如果数据库中不存在请求的ID,我想将用户重定向到错误页面。我的代码:

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);
    }

这不起作用,如果输入false id,则会出现服务器错误。

2 个答案:

答案 0 :(得分:1)

使用.FirstOrDefault()代替.First()。如果没有找到记录而不是抛出异常,则返回null:

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

现在您可以检查DAVM.Ad是否为空:

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

答案 1 :(得分:0)

找到解决方案:

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" });
        }
    }