我在try catch块中得到错误'并非所有代码路径返回值'

时间:2014-03-31 00:13:46

标签: c# asp.net-mvc

请看下面的代码,它是MVC,我试图创建一个IEnumerable视图。我得到的错误是并非所有代码路径都返回一个值'我该如何纠正错误?

public class CustomerSummary
{
    public string ContactName { get; set; }     // Customer table
    public string City { get; set; }            // Customer table
    public string PostalCode { get; set; }      // Order table
    public string ShipName { get; set; }        // Order table
    public string ProductName { get; set; }     // Product table
    public bool Discontinued { get; set; }      // product table

}

控制器

public class CustomerSummaryController : Controller
{
    //
    // GET: /CustomerSummary/
    private CustomerSummaries _customerSummaries = new CustomerSummaries();

    public ViewResult Index()
    {
        IEnumerable<CustomerSummary> summaries = _customerSummaries.GetAll();
        return View(summaries);
    }

}

数据层

public IEnumerable<CustomerSummaries> GetAll(/* to do put connection string here */)
    {
        try
        {
            SqlCommand cmd = new SqlCommand("GetAll", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            SqlDataReader sdr;
            conn.Open();
            sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {
                if (sdr.IsDBNull(sdr.GetOrdinal("ContactName")) != true)
                {
                    sdr["ContactName"].ToString();
                }
            }


        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            conn.Close();
        }
    } 

1 个答案:

答案 0 :(得分:0)

我在这里做了相当多的假设,但我认为这就是你想要的:

public IEnumerable<CustomerSummary> GetAll(SqlConnection conn)
{
    var result = new List<CustomerSummary>();

    try
    {
        SqlCommand cmd = new SqlCommand("GetAll", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        SqlDataReader sdr;
        conn.Open();
        sdr = cmd.ExecuteReader();
        while (sdr.Read())
        {
            var cs = new CustomerSummary();

            if (sdr.IsDBNull(sdr.GetOrdinal("ContactName")) != true)
            {
                cs.ContactName = sdr["ContactName"].ToString();
            }

            // repeat the above if-block to add more info if needed...

            // add the CustomerSummary to the result
            result.Add(cs);
        }
    }
    catch (Exception)
    {
        throw;
    }
    finally
    {
        conn.Close();
    }

    return result;
}