【问题标题】:How to call stored procedure in MVC controller ? [duplicate]如何在 MVC 控制器中调用存储过程? [复制]
【发布时间】:2012-10-15 07:28:52
【问题描述】:

可能重复:
ASP.NET MVC: Best Way To Call Stored Procedure

我正在开发 MCV3 应用程序。

我想在应用程序的控制器之一中调用存储过程。

我已经将存储过程保存在我用于应用程序的数据库中。

查询是

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

现在,我想将此过程调用到控制器中...

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...


        }
    }
}

怎么称呼它?

【问题讨论】:

    标签: sql-server asp.net-mvc-3 stored-procedures


    【解决方案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();
    }
    

    【讨论】:

    • 谢谢,我会的...但是在我的 web.config 文件中,我遵循字符串...。我可以按原样使用它吗? &lt;add name="CRMWebContainer" connectionString="metadata=res://*/CRMWeb.csdl|res://*/CRMWeb.ssdl|res://*/CRMWeb.msl;provider=System.Data.SqlClient;provider connection string=&amp;quot;data source=ADSERVER;initial catalog=CRMWEBLIVE11OCT;user id=sa;password=myfair@123;multipleactiveresultsets=True;App=EntityFramework&amp;quot;" providerName="System.Data.EntityClient" /&gt;
    • 这不是纯连接字符串。它使用 EntityFrameWork 模型生成。如果您使用 ADO.net 并希望从 web.config 获取连接字符串,请首先将 connectionString 属性更改为:data source=ADSERVER;initial catalog=CRMWEBLIVE11OCT;user id=sa;password=myfair@123;
    • 如果我想使用 ConnectionString,我必须做出哪些改变。如果我想使用“CRMWebContainer”名称,连接字符串名称怎么办?
    • 嘿伙计,google 是你的朋友 ;) ,使用这个:ConfigurationManager.ConnectionStrings["CRMWebContainer"] 记得使用 System.Configuration 添加
    • 我在 webconfig &lt;add name="CRMWebContainer" connectionString="metadata=res://*/CRMWeb.csdl|res://*/CRMWeb.ssdl|res://*/CRMWe‌​b.msl;provider=System.Data.SqlClient;provider connection string=&amp;quot;data source=ADSERVER;initial catalog=CRMWEBLIVE11OCT;user id=sa;password=myfair@123;multipleactiveresultsets=True;App=EntityFramework&amp;quot‌​;" providerName="System.Data.EntityClient" /&gt; 中有以下代码行,我使用下面的代码行获取连接字符串 string strConnectionString = ConfigurationManager.AppSettings["CRMWebContainer"]; 它返回 null。
    猜你喜欢
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 2021-05-13
    • 2012-12-16
    • 1970-01-01
    相关资源
    最近更新 更多