asp.net-mvc – ASP.NET MVC:调用存储过程的最佳方式

我试图决定哪个是调用存储过程的最佳方法.

我是ASP.NET MVC的新手,我一直在阅读很多关于Linqsql和实体框架,以及Repository Pattern.说实话,我很难理解L2S和EF之间的真正差异,但我想确保我在应用程序中构建的是正确的.

对于现在,我需要正确地调用存储过程:a)保存一些用户信息并得到响应,b)为产品目录获取一些信息.

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

MyLinqModel _db = new MyLinqModel();
_db.MyStoredProcedure(args);

我知道有更多的参与…加上我在我的控制器里这样做,我明白这不是一个好的做法.

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

解决方法

如果你想要做的就是调用存储过程,LINQ和EF可能是过度的.

我使用企业库,但ADO.NET也可以正常工作.

this tutorial.

简短地(从参考文章中无耻地复制和粘贴):

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.

MSDN has a decent tutorial on the topic.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....