gpt4 book ai didi

asp.net-mvc - ASP.NET MVC : Best Way To Call Stored Procedure

转载 作者:行者123 更新时间:2023-12-04 00:48:40 25 4
gpt4 key购买 nike

我正在尝试确定调用存储过程的最佳方式。

我是 ASP.NET MVC 的新手,我已经阅读了很多关于 Linq to SQL 和 Entity Framework 以及存储库模式的内容。老实说,我很难理解 L2S 和 EF 之间的真正区别……但我想确保我在应用程序中构建的内容是正确的。

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

到目前为止,我已经创建了一个 Linq to SQL .dbml 文件,从服务器资源管理器中选择了 sotred 过程并将该实例拖到 .dbml 中。我目前正在像这样调用存储过程:

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

我知道必须有更多的参与......而且我正在我的 Controller 中这样做,我理解这不是一个好的做法。

有人能认出我的问题是什么吗?

最佳答案

如果您尝试做的只是调用存储过程,则 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"]);
}
}

更新

我错过了您说您在 Controller 中执行此操作的部分。

不,这不是正确的做法。

您的 Controller 应该只参与编排 View 构建。创建一个单独的类库,称为“数据访问层”或不那么通用的东西,并创建一个处理调用存储过程、从结果创建对象等的类。 关于如何处理这个问题有很多意见,但也许是最常见的是:
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.

关于asp.net-mvc - ASP.NET MVC : Best Way To Call Stored Procedure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4259989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com