0

我最近发现了使用存储库的好处,我对此很陌生,我的问题是我现在如何返回代码?例如,在我使用存储库之前,在我的常规控制器中,我返回这样的代码

public ActionResult Index(int? zips, double? rad)
    {


        if (!zips.HasValue)
        {

            string connectme = ConfigurationManager.ConnectionStrings["looglercontext"].ConnectionString;
            using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(connectme))
            {
                sqlConnection.Open();
                var articles = sqlConnection.Query<Article>("Select top 20 * from articles").ToList();
                return View(new homepage { article = articles });
            }
        }
        return View();
    }

现在我将该代码放入存储库中,因为他们不带 ViewModels 返回我基本上迷路了这就是我所拥有的

public homepage FirstRepository(int? zips, double? rad)
  {
      if (!zips.HasValue)
      {

          string connectme = ConfigurationManager.ConnectionStrings["looglercontext"].ConnectionString;
          using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(connectme))
          {
              sqlConnection.Open();
              var articles = sqlConnection.Query<Article>("Select top 20 * from articles").ToList();
              return  new homepage { article = articles};
          }
      }

// 如果存储库为空,我如何在这里返回一些东西 }

我收到错误并非所有代码路径都返回一个值

4

1 回答 1

0

为了编译此代码,如果您的if条件不满足,您可以返回一个空列表:

public IList<Article> FirstRepository(int? zips, double? rad)
{
    if (!zips.HasValue)
    {
        string connectme = ConfigurationManager.ConnectionStrings["looglercontext"].ConnectionString;
        using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(connectme))
        {
            sqlConnection.Open();
            var articles = sqlConnection.Query<Article>("Select top 20 * from articles").ToList();
            return articles;
        }
    }

    return new List<Article>();
}

然后在你的控制器中:

public ActionResult Index(int? zips, double? rad)
{
    var articles = someRepo.FindRepository(zips, rad);
    return View(new homepage { articles = articles });
}
于 2013-09-22T14:28:39.810 回答