[英]C# code and SQL Server 2008 stored procedure performance comparison
[英]A good way to access stored procedure on SQL Server 2008 from C#
我試圖從我的ASP.NET / C#web應用程序訪問存儲過程。
是否有一種特別好的方法(也是將參數傳遞給它的好方法)?
我按照以下步驟操作,絕對不喜歡這種方法,因為您將該過程作為字符串輸入(不可調試): http ://www.c-sharpcorner.com/UploadFile/dclark/InsOutsinCS11302005072332AM/InsOutsinCS.aspx
如果你使用LinqToSQL,ScottGU有一些關於這個主題的優秀博客文章 。
我喜歡SubSonic 。 SubSonic將根據您的數據庫架構為您生成DAL。 大多數人使用生成的SubSonic對象和activerecord或simplerepository模式來處理數據庫,但Subsonic也會生成強類型方法來包裝存儲過程和視圖。
這是一個相當基本的示例,但您可以進行類似於以下內容的存儲過程調用:
SubSonic.StoredProcedure sp = Dal.StoredProcedures.UpdatePassword(id, pw);
DataSet ds = sp.GetDataSet();
在上面的代碼中,StoredProcedures類包含UpdatePassword存儲過程的強類型方法。 這對我很有效。
使用LINQ to SQL或Entity Framework確實可以為您提供對參數和結果的強大類型訪問,但在使用它們之前需要做很多考慮。 LINQ to SQL是臨終關系,Entity Framework將在.NET Framework 4.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;
}
}
}
}
}
}
是的,這是相當多的代碼,所以如果你想要使用vanilla ADO.NET,你可能想要編寫一些輔助方法。
最好的方法是使用LINQ to SQL或ADO.NET實體。 Visual Studio將為您的存儲過程生成相應的強類型方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.