2012-10-15 24 views
0

可能重複:
ASP.NET MVC: Best Way To Call Stored Procedure如何在MVC控制器中調用存儲過程?

我開發MCV3應用。

我想在應用程序的控制器之一調用存儲過程。

我已經將存儲過程保存在我正在用於應用程序的數據庫中。

查詢是

Create Procedure ConvertLeadToCustomer1 
@CompanyID int 
as 
begin 
update Companies set __Disc__ = 'Customer' where CompanyID = @CompanyID 
end 

現在,我婉稱這種procesure到控制器...

namespace CRMWeb.Controllers 
{ 
    public class LeadController : Controller 
    { 
     private CRMWebContainer db = new CRMWebContainer(); 

     // 
     // GET: /Lead/ 

     public ViewResult Index() 
     { 
      //return View(db.Companies.ToList()); 
      return View(db.Companies.OfType<Lead>().ToList()); 

     } 

      public ActionResult Convert(int id) 
     { 

      // I want to write code here to call stored procedure... 


     } 
    } 
} 

如何稱呼呢?

回答

1

它在MVC沒有什麼不同,如果用ADO.net,下面的代碼調用存儲過程:

public ActionResult Convert(int id) 
{ 
    var connection = new SqlConnection("YOUR CONNECTION STRING"); 

    var command = new SqlCommand("ConvertLeadToCustomer1",connection) 
    command.CommandType = CommandType.StoredProcedure; 
    command.Parameters.AddWithValue("@CompanyID", id); 

    connection.Open(); 

    command.ExcuteNonQuery(); 

    connection.Close(); 
} 
+0

謝謝,我會這樣......但在我的web.config文件我ahev以下字符串.. ..我可以使用它嗎? '' – user1668543

+0

this不是純粹的連接字符串。它使用EntityFrameWork模型生成。如果您使用ADO.net並希望從web.config中獲取連接字符串,請首先將connectionString屬性更改爲:data source = ADSERVER; initial catalog = CRMWEBLIVE11OCT; user id = sa; password = myfair @ 123; – mhdrad

+0

非常感謝...它的工作原理... – user1668543

相關問題