我是 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/