C# 从C访问SQLServer2008上存储过程的一种好方法
我正在尝试从ASP.NET/C web应用程序访问存储过程 有没有一种特别好的方法可以做到这一点,也有一种将参数传递给它的好方法C# 从C访问SQLServer2008上存储过程的一种好方法,c#,asp.net,ado.net,C#,Asp.net,Ado.net,我正在尝试从ASP.NET/C web应用程序访问存储过程 有没有一种特别好的方法可以做到这一点,也有一种将参数传递给它的好方法 我遵循以下步骤,绝对不喜欢这种方法,因为您将过程作为不可调试的字符串输入:最好的方法是使用LINQ to SQL或ADO.NET实体。Visual Studio将为您的存储过程生成相应的强类型方法。如果要使用LinqToSQL,ScottGU在这方面有一些优秀的方法 我喜欢。亚音速将根据您的数据库模式为您生成DAL。大多数人使用生成的带有activerecord或si
我遵循以下步骤,绝对不喜欢这种方法,因为您将过程作为不可调试的字符串输入:最好的方法是使用LINQ to SQL或ADO.NET实体。Visual Studio将为您的存储过程生成相应的强类型方法。如果要使用LinqToSQL,ScottGU在这方面有一些优秀的方法 我喜欢。亚音速将根据您的数据库模式为您生成DAL。大多数人使用生成的带有activerecord或simplerepository模式的亚音速对象来处理数据库,但亚音速也生成强类型方法来包装存储过程和视图 这是一个相当基本的示例,但您可以进行类似于以下内容的存储过程调用:
SubSonic.StoredProcedure sp = Dal.StoredProcedures.UpdatePassword(id, pw);
DataSet ds = sp.GetDataSet();
在上面的代码中,StoredProcedures类包括UpdatePassword存储过程的强类型方法。这对我很有用
使用linqtosql或Entity框架确实为您提供了对参数和结果的良好强类型访问,但是在使用它们之前,需要考虑很多因素。LINQ到SQL已经过时,实体框架将在.NETFramework4.0中得到重大改进 为了做出明智的考虑,我想我应该分享低级ADO.NET的做事方式:
void CallMyStoredProcedure(string connectionString, string paramValue)
{
string spName = "MyStoredProcedure";
string columnValue;
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(spName, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// Set parameter values
cmd.Parameters.AddWithValue("@inputParam",
(object)paramValue ?? DBNull.Value);
// Parameter to store return value of your SP
SqlParameter returnParam = cmd.Parameters.Add(
new SqlParameter("RETURN_VALUE", SqlDbType.Int));
returnParam.Direction = ParameterDirection.ReturnValue;
// Execute SP and read results
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
// Do something with return value
int? returnValue = cmd.Parameters["RETURN_VALUE"].Value as int?;
while (dr.Read())
{
// Suggested way to read results if you use
// "SELECT * FROM" in your SP. If you return columns
// in a fixed order, it's fairly safe to be reading
// in that order without looping
for (int field = 0; field < dr.FieldCount; field++)
{
switch (dr.GetName(field))
{
case "StringColumn":
columnValue = dr.GetValue(field) as string;
break;
default:
// Column not recognized by your code.
// You might choose to complain about it here.
break;
}
}
}
}
}
}
是的,这是一段相当多的代码,所以如果你想使用普通的ADO.NET,你可能想编写一些帮助方法。你有没有实现这一点的方法/方法或教程?你没有仔细阅读那篇文章。您不以字符串形式输入过程,只输入其名称。