How to connect ado.net database to ASP.Net MVC 5

10,780

There's nothing stopping you from using ADO.NET in MVC.Entity Framework is a very popular ORM and it's really simple to set up that's why people like using it for tutorials.But if you need a more custom\controlled way of accessing your data you can still use ADO.NET.

Just a tip - don't store your connection in code, that's considered bad practice.If the database is moved to a different server you will need to change code and re-compile the whole application.You should store the connection string in the *.config file:

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

And can access it from your code like this:

string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
Share:
10,780
Manish Tiwari
Author by

Manish Tiwari

Updated on June 04, 2022

Comments

  • Manish Tiwari
    Manish Tiwari almost 2 years

    I'm new to ASP.Net MVC 5 and have previously created two applications using ASP.Net Webforms and Ado.Net Database connections.

    I've seen many articles explaining how to use Ado.Net connection in ASP.Net MVC, but all the tutorials are using Entity Framework. Is there any way to connect only Ado.Net?

    In my WebForm application I've been using this connection code:

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

    Is it possible to use this in ASP .Net MVC5?

    When I tried I got this error:

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

    This is the code I tried using:

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