如何解决在 ASP.NET Core 3.1/5.0 中调用存储过程
我有一个简单的 ASP.NET Core 服务,它需要与数据库进行一次交互。它调用返回 BigInt
/long
的存储过程。
为此启动所有东西来运行 Entity Framework Core 似乎有点矫枉过正。特别是因为 EF Core 并没有很好地执行存储过程(截至我上次检查)。
是否只有 .NET Core 可以调用和获取存储过程的结果(不使用 EF Core 或其他框架)?
解决方法
这样的东西是您需要的最低限度。显然,您可能希望将连接字符串存储在配置文件中。
await using DbConnection connection = new SqlConnection("Connection_String");
await connection.OpenAsync();
await using var command = connection.CreateCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "Stored_Proc_Name";
// Declare any parameters here
var p = command.CreateParameter();
p.ParameterName = "IsCool";
p.Value = true;
p.DbType = System.Data.DbType.Boolean;
command.Parameters.Add(p);
var result = await command.ExecuteScalarAsync();
if (result == null) {
throw new Exception("Bad");
}
long numValue = (long) result;
,
我在 .NET Core 5 Web 应用程序中遇到了与 Razor 页面类似的问题。为了使连接字符串进入作用域,我必须将配置注入到类中。代码如下所示:
public class AskSQLModel : PageModel
{
public AskSQLModel(IConfiguration _config)
{
this.Configuration = _config;
}
public IConfiguration Configuration { get; set; }
/// <summary>
/// Property to hold value returned from stored procedure
/// </summary>
public long ReturnValue { get; set; }
public void OnGet()
{
string cn = this.Configuration["ConnectionStrings:SQLConnect"];
SqlCommand cmd = new SqlCommand();
cmd.Connection = new SqlConnection(cn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "GetLong";
cmd.Connection.Open();
ReturnValue = (long)cmd.ExecuteScalar();
cmd.Connection.Close();
}
}
Razor 页面代码如下所示:
@page
@model AskSQLModel
@{
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>This page will get a value from SQL Server.</p>
<h4>The value is: @Model.ReturnValue</h4>
</div>
最后生成的页面显示:
Welcome
This page will get a value from SQL Server.
The value is: 17
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。