3

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" />

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, this is added into my model, and the web.config updated, i now get this error.. The network path was not found through the WebSecurity.InitializeDatabaseConnection() method used for User logins, any ideas?
Is your DBContext in a seperate assembly? If so, make sure your connection string defined in the web application config as well as that of the assembly.
Hi Jack. Did adding the connection string to the web.config file resolve the issue? If so can you please mark the question as answered?
Hi, i have updated my question with what i found to fix my issue, Thanks Rob

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.