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

时间:2016-07-03 04:24:57

标签: 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();
}

1 个答案:

答案 0 :(得分:3)

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

只是一个提示 - 不要将您的连接存储在代码中,这被认为是不好的做法。如果数据库被移动到另一个服务器,您将需要更改代码并重新编译整个应用程序。您应该存储连接字符串在Web.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;