ASP.NET MVC:调用存储过程的最佳方法

dco*_*bus 12 asp.net-mvc stored-procedures linq-to-sql

我正在尝试确定哪个是调用存储过程的最佳方法.

我是ASP.NET MVC的新手,我已经阅读了很多关于Linq to SQL和Entity Framework以及Repository Pattern的内容.说实话,我很难理解L2S和EF之间的真正差异......但我想确保我在我的应用程序中构建的内容是正确的.

目前,我需要正确调用存储过程:a)保存一些用户信息并获得响应,b)获取产品目录的一些信息.

到目前为止,我已经创建了一个Linq to SQL .dbml文件,从Server Explorer中选择了sotred过程并将该实例拖到.dbml中.我正在调用存储过程,如下所示:

MyLinqModel _db = new MyLinqModel();
_db.MyStoredProcedure(args);
Run Code Online (Sandbox Code Playgroud)

我知道必须更多地参与......而且我在我的控制器中这样做,我理解这不是一个好习惯.

有人能认出我的问题在这里吗?

3Da*_*ave 19

如果你要做的就是调用存储过程,那么LINQ和EF可能有点过分.

我使用Enterprise Library,但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"]);
        }
    }
Run Code Online (Sandbox Code Playgroud)

更新

我错过了你说你在你的控制器中这样做的部分.

不,这不是正确的方法.

您的控制器应该只涉及编排视图构造.创建一个单独的类库,称为"数据访问层"或不太通用的东西,并创建一个类来处理调用存储过程,从结果中创建对象等.关于如何处理它有很多意见,但也许是最常见的是:

View
|
Controller
|
Business Logic
|
Data Access Layer
   |--- SQL (Stored procs)
           -Tables
           -Views
           -etc.
   |--- Alternate data sources
           -Web services
           -Text/XML files
           -blah blah blah.
Run Code Online (Sandbox Code Playgroud)

MSDN有一个关于这个主题的体面教程.

  • 是的.知道一个开发人员认为企业库比ado.net更快的人.我喜欢企业库,但是DAAB包装了ado.net,因此声称速度更快是非常愚蠢的.伙计们,了解你的工具! (3认同)