3

I seem to have an issue creating an MVC4 application where I have adopted the code-first approach to creating my models but no connection string seems to have been created in the web.config file.

The constructed database seems to have been built on (localhost)\SQLEXPRESS instance but I would like to change this to an external data source. Without a connection string to update I'm not sure how to do this.

Please could someone point me in the right direction?

EDIT: I found the following diagram which highlights what the answers have said pretty well

EF DB Initialization Flowchart
(source: entityframeworktutorial.net)

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Chris Pickford
  • 8,642
  • 5
  • 42
  • 73

3 Answers3

2

You have to add a connection string yourself

<add name="SomeDb" connectionString="Data Source=SERVENAME;Initial Catalog=DBNAME;User Id=loginid;Password=password" providerName="System.Data.SqlClient" />

Name of this string should match to the name of your context class.

public class SomeDb: DbContext
{
    public SomeDb()
        : base("name=SomeDb")
    { 
    }
}

This should do it.

HBhatia
  • 555
  • 1
  • 6
  • 21
  • if i have used windows auth instead of SQL server auth while connecting to server what user id and password i should give in the connection string? – Gururaj Oct 26 '22 at 04:59
1

You have to create a connection string with the same name as your DbContext class:

<connectionStrings>
    <add name="NameOfDbContext" connectionString="Data Source=ServerName\InstanceName;Initial Catalog=DatabaseName;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

You can also specify the connection string yourself using an overload of the DbContext class:

public class MyDbContext() : base("ProductionDbContext")
{
}

Now you can use ProductionDbContext as connection string.

See this article on MSDN for more information.

Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
1

If you use ADO.NET Entity Framework(.edmx) it will update your web.config file with connection string. but in code-first you need to write your connection string in web.config like,

suppose you dbcontext looks like,

public class SampleDbContext:DbContext
{
public SampleDbContext():base("SampleDbContext")
{

}
...
...
}

after you should create your connection string in web.config with SampleDbContext name like,

Hope this helps

Karthik Bammidi
  • 1,851
  • 9
  • 31
  • 65