Asp.net-Mvc
ASP.NET MVC:呼叫儲存過程的最佳方式
我正在嘗試確定哪種方法是呼叫儲存過程的最佳方式。
我是 ASP.NET MVC 的新手,我已經閱讀了很多關於 Linq to SQL 和實體框架以及儲存庫模式的內容。老實說,我很難理解 L2S 和 EF 之間的真正區別……但我想確保我在應用程序中建構的內容是正確的。
現在,我需要正確呼叫儲存過程來:a)保存一些使用者資訊並獲得響應,b)獲取產品目錄的一些資訊。
到目前為止,我已經創建了一個 Linq to SQL .dbml 文件,從伺服器資源管理器中選擇了 sotred 過程並將該實例拖到 .dbml 中。我目前正在呼叫儲存過程,如下所示:
MyLinqModel _db = new MyLinqModel(); _db.MyStoredProcedure(args);我知道必須有更多的參與……而且我在我的控制器中這樣做,我知道這不是一個好習慣。
有人能認出我的問題在這裡嗎?
如果您想要做的只是呼叫儲存過程,那麼 LINQ 和 EF 可能會過大。
我使用企業庫,但 ADO.NET 也可以正常工作。
請參閱本教程。
簡要地(從引用的文章中無恥地複制和粘貼):
SqlConnection conn = null; SqlDataReader rdr = null; // typically obtained from user // input, but we take a short cut string custId = "FURIB"; Console.WriteLine("\nCustomer Order History:\n"); // create and open a connection object conn = new SqlConnection("Server=(local);DataBase=Northwind; Integrated Security=SSPI"); conn.Open(); // 1. create a command object identifying // the stored procedure SqlCommand cmd = new SqlCommand( "CustOrderHist", conn); // 2. set the command object so it knows // to execute a stored procedure cmd.CommandType = CommandType.StoredProcedure; // 3. add parameter to command, which // will be passed to the stored procedure cmd.Parameters.Add( new SqlParameter("@CustomerID", custId)); // execute the command rdr = cmd.ExecuteReader(); // iterate through results, printing each to console while (rdr.Read()) { Console.WriteLine( "Product: {0,-35} Total: {1,2}", rdr["ProductName"], rdr["Total"]); } }更新
我錯過了您說您在控制器中執行此操作的部分。
不,這不是正確的做法。
您的控制器實際上應該只參與編排視圖建構。創建一個單獨的類庫,稱為“數據訪問層”或不太通用的東西,並創建一個處理呼叫儲存過程、從結果創建對像等的類。關於如何處理有很多意見,但也許最常見的是:
View | Controller | Business Logic | Data Access Layer |--- SQL (Stored procs) -Tables -Views -etc. |--- Alternate data sources -Web services -Text/XML files -blah blah blah.