我得到了错误'不是所有的代码路径都返回值'在try catch block中
本文关键字:返回值 路径 try 代码 block catch 错误 | 更新日期: 2023-09-27 17:55:04
请参阅下面的代码,这是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();
}
}
我在这里做了相当多的假设,但我认为这是你想要的:
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;
}