c# - 如何将 ado.net 数据库连接到 ASP.Net MVC 5

标签 c# asp.net asp.net-mvc asp.net-mvc-5 ado.net

我是 ASP.Net MVC 5 的新手,之前使用 ASP.Net Webforms 和 Ado.Net 数据库连接创建了两个应用程序。

我看过很多文章解释如何在 ASP.Net MVC 中使用 Ado.Net 连接,但所有教程都使用 Entity Framework 。有没有办法只连接Ado.Net?

在我的 WebForm 应用程序中,我一直在使用以下连接代码:

connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "SQL Statement";
cnn = new SqlConnection(connectionString);
try
{
    cnn.Open();
    cmd = new SqlCommand(sql, cnn);
    cmd.ExecuteNonQuery();
    cmd.Dispose();
    cnn.Close();
}

可以在 ASP .Net MVC5 中使用它吗?

当我尝试时,我收到此错误:

Cannot open database "online_recharge" requested by the login. The login failed.
Login failed for user 'IIS APPPOOL\DefaultAppPool'.

这是我尝试使用的代码:

public ActionResult Add_Balance()
{
    string record;

    using (SqlConnection sqlConnection = new SqlConnection(connectionString))
    {
        sqlConnection.Open();
        SqlCommand sqlCmd = new SqlCommand("Select * from COMMISSION_PACKAGE",sqlConnection);
        SqlDataReader reader = sqlCmd.ExecuteReader();
        record = reader["PKG_NM"].ToString();
        sqlConnection.Close();
    }

    ViewBag.Demo = record;
    return View();
}

最佳答案

没有什么可以阻止您在 MVC 中使用 ADO.NET。Entity Framework 是一种非常流行的 ORM,而且设置起来非常简单,这就是人们喜欢在教程中使用它的原因。但是,如果您需要更自定义\受控的访问方式您仍然可以使用 ADO.NET 的数据。

只是一个提示 - 不要将连接存储在代码中,这被认为是不好的做法。如果数据库移动到不同的服务器,您将需要更改代码并重新编译整个应用程序。您应该存储连接字符串在 *.config 文件中:

  <connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"/>
  </connectionStrings>

并且可以从您的代码中访问它,如下所示:

string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

关于c# - 如何将 ado.net 数据库连接到 ASP.Net MVC 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38166718/

相关文章:

c# - 在 LiteDB c# .net 中获取最新插入

c# - WCF 中的基础结构和应用程序端点之间有什么区别(通俗地说)?

java - 在使用原始表单数据的网站上填写登录表单

c# - 在asp.net mvc4中动态添加DisplayName属性

c# - 带字符串数组的串联 Where 子句

c# - 当用户在代理后面时从客户端应用程序访问 WCF 服务

c# - 如何在一个变量中存储多个状态?

c# - 在 asp.net 中验证密码

asp.net - 如何在我的 MVC3 模型绑定(bind)中包含 Telerik 文件上传?

c# - Web API 2 返回文本/纯文本响应