Jack Allen
Jack Allen

Reputation: 547

Connect to a database from Web.Config <appSettings> section C# / MVC

I'm currently connected to a database using

Web.Config

<connectionStrings>
    <add name="MVCDatabase" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MVCDatabase.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Controller

public MVCDatabase db = new MVCDatabase();

Model

public class MVCDatabase : DbContext
{
    public DbSet<Things> Tables2 { get; set; }
    public DbSet<OtherStuff> Table2{ get; set; }
} 

is there a way of moving the database connection string, and it still working in the controller etc, to the [appSettings] section in the Web.Config file?

Web.Config Example

<appSettings>
     <add key="ConnectionString" value="Server=dbserver; Database=mvcdatabase; User Id=username; Password=password"/>
</appSettings>

Edit (Fix)

After searching loads, i worked out that i needed to and put it in generate a machine key and place it in my web.config file

something like this

<machineKey validationKey="8AA518FA814CFC6572AFD7E3E1139D1AE5A3CE9B4952B2BD2DABC1428C3CC85842A4F1060E02F8EDFA2FD5CE7AAD0F67EF9842AA96186544F4A6D5ED3444AC48" decryptionKey="9F2CABCCBC0EA7CD6B96BD263AB78962D1577AB557BB7422" validation="SHA1" />

Upvotes: 3

Views: 13472

Answers (1)

Rob King
Rob King

Reputation: 1201

Try this:

  1. Reference System.Configuration

  2. Add this at the top of the file:

    using System.Configuration;
    

Then change your model by adding a constructor as follows:

public class MVCDatabase : DbContext
{
    public MVCDatabase() : base(ConfigurationManager.AppSettings["ConnectionString"])
    {
    }

    ...
}

Then set up the config file as you said in your question. What is certain, is that the constructor will accept either the name of the config element (where it assumes its on connectionStrings) or the explicit connection string, which ConfigurationManager should return.

Upvotes: 2

Related Questions