写我的数据访问层方法的正确方法是什么?
本文关键字:方法 是什么 数据 访问 我的 | 更新日期: 2023-09-27 18:05:54
这样够好吗?我需要添加或删除任何东西吗?像回滚到我的Sql查询?添加catch() ?我的函数应该只接受我需要的属性还是它自己的对象?我怎样才能让表示层知道函数的代码没有错误地执行。我应该把它改成book而不是void还是怎样?
public static void DeleteAllCabinFeaturesFromACruise(int CruiseID)
{
string commandText = "DELETE FROM Cruise_Features WHERE CruiseID = @cruiseId";
SqlConnection connection = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(commandText, connection);
try
{
using (connection)
{
using (command)
{
command.Parameters.AddWithValue("@cruiseId", CruiseID);
connection.Open();
command.ExecuteScalar();
}
}
}
finally { connection.Close(); }
}
您没有正确使用using
。using
的想法是包装一些资源,这些资源需要在安全的西部释放,以保护它免受异常的影响。所以,正确使用using
(哈哈)的方法如下:
using(SqlConnection connection = new SqlConnection(ConnectionString)){
{
using(SqlCommand command = new SqlCommand(commandText, connection)){
//your code here
}
}
第二个问题是,您正在执行查询,好像它应该返回标量值。这是可以的,但我认为最好只使用Execute
: command.Execute();
,如果你想要一些错误处理,你最好包装
connection.Open();
command.ExecuteScalar();
在try ... catch
块像你有。这样的:
//I would place it inside inner-most using block, but nothing wrong placing it outside
try{
connection.open();
command.Parameters.AddWithValue("@cruiseId", CruiseID);
command.Execute();
}
//this catches ALL exceptions, regardless of source. Better narrow this down with
//some specific exception, like SQLException or something like that
catch (Exception e){
return false; //or whatever you need to do
}
可以删除try…finally块。"using"将为您处理连接。
EDIT:正如chibacity所说,您应该在使用中初始化连接以确保正确的处置。错误处理(防止用户看到异常细节)应该在UI层完成,而不是数据层。数据层抛出异常是完全合适的。
string commandText = "DELETE FROM Cruise_Features WHERE CruiseID = @cruiseId";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
// Your code.
}
对于这样一个简单的查询,回滚可能是不必要的——查询要么成功,要么失败。对于更复杂的查询,如果希望确保操作是原子的,则需要回滚。
以及如何让表示层知道函数的代码没有错误地执行?
这实际上归结为你想要如何处理这些情况。一个经验法则是问自己一个问题;您是否期望经常发生严重的错误?因此,例如,如果方法只有在出现通信错误时才会失败,那么向前端抛出异常是完全可以的。另一方面,如果删除操作可能因为需要验证的各种业务规则而失败(或者,例如,违反外键),那么您可能不应该将它们作为异常抛出。在后一种情况下,您的方法应该返回一些关于成功的信息(简单版本:一个布尔值,复杂版本:您自己的"OperationResult"类)。
我在这里简化了很多东西,但我相信这些经验法则是有效的。
编辑:当我说"那么抛出一个异常到前端是完美的",我的意思是——把它扔到前端,但让前端优雅地处理它!
connection. close()是多余的-使用(connection)将处理并关闭它。此外,connection. open()通常放在开头-用于验证与服务器的连接。