Free Web Development Online Tutorials, Learn to Code
Learn Database connection in MVC, How to connect database in MVC

Database connection string in MVC

Connect database in MVC

Now we learn how to connect database using database connection string in MVC application

Database connection string in Web.Config

Open your web.config file in root of your web application, Now you can setup your database connection details in two ways.

1. Set up connectionString property directly in webconfig with right providerName.
<add name="DefaultConnection" connectionString="Data Source=;Initial Catalog=WTRAppDatabase;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

2. In web.config file appSettings section adding each property value then read the value and form the connection string in your code.

<add key="ServerName" value=""/>
<add key="DatabaseName" value="WTRAppDatabase"/>
<add key="SchemaName" value="dbo"/>
<add key="UserId" value="dbuser100"/>
<add key="Password" value="xxpassword123"/>

Read Database connection string in C#

Now read the database connection details in your C# code, create a utility class like below

//namespace required
using System.Configuration;
using System.Text;
using System.Data.Entity;
using System.Data.EntityClient;
using System.Data.SqlClient;         

public static string DBConnectionString
    SqlConnectionStringBuilder providerCs = new SqlConnectionStringBuilder();
    providerCs.InitialCatalog = ConfigurationManager.AppSettings["DatabaseName"];
    providerCs.UserID = ConfigurationManager.AppSettings["UserId"];
    providerCs.Password = ConfigurationManager.AppSettings["Password"];
    providerCs.DataSource = ConfigurationManager.AppSettings["ServerName"];               

    providerCs.MultipleActiveResultSets = true;
    providerCs.TrustServerCertificate = false;
    providerCs.IntegratedSecurity = true;            

    return providerCs.ToString();

Note: in real life, you may need to keep encrypted username and password in web.config, in that case you simply decrypt the property value by using your encryption utility this way

providerCs.InitialCatalog = UtilityService.Decrypt(ConfigurationManager.AppSettings["DatabaseName"]);

Your connectionString is ready to be used in your class.

entityframework connection string

Now if you are using entityframework, then adding below code will make the job easier.

EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder();
ecsb.Provider = "System.Data.SqlClient";
ecsb.ProviderConnectionString = providerCs.ToString();
ecsb.Metadata = string.Format("res://{0}/entityfilename.csdl|res://{0}/entityfilename.ssdl|
res://{0}/entityfilename.msl", typeof(Entities).Assembly.FullName);

Another way could be instead of keeping the connectionstring details in web.config file, keep them in a separate xml file and read the file using .net configuration framework