How do I tell EF what to name the database and where to put it?
If there is no connection string in the Web.Config, it tries to put it in the local SQLEXPRESS Server
As already mentioned, you can declare your connection string inside the config file of your application with a name (let's say "YourDBName") and then pass this to the DbContext
base constructor call (I will add this to the answer for providing a complete answer - great answers already given on this).
Alternatively, you can set this programmatically in your DbContext
Extension class, using the Database.Connection.ConnectionString
property. For instance:
App.config:
<!-- More.... -->
<!-- You can do this in a declarative way -->
<connectionStrings>
<add name="YourDBName"
connectionString="<Your connection string here>"
providerName="<Your provider here>" />
</connectionStrings>
<!-- More.... -->
DatabaseContext.cs:
public class DatabaseContext : DbContext
//Link it with your config file
public DatabaseContext () : base("YourDBName")
{
//And/Or you can do this programmatically.
this.Database.Connection.ConnectionString = "<Your Connection String Here>";
// More Stuff.....
}
}
Alternatively you can set the name in your DbContext constructor.
If you point your connection-string at an existing database then EF “code first” will not try and create one automatically.
EF “code first” uses a convention where context classes by default look for a connection-string that has the same name as the context class.
Using ef code first with an existing database
Create a connection string in the app.config/web.config with the same name as the context and the EF will use that DB.
in Class :
public class Context : DbContext
{
//SET CONNECTION STRING NAME FOR DataBase Name :
public Context() : base("YourConnectionName") { }
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
}
in web.config:
<connectionStrings>
<add name="YourConnectionName" connectionString="Data Source=A-PC\SQLEXPRESS;
Initial Catalog=MyDataBase; Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Thanks ferventcoder.
Ref => http://brandonclapp.com/connection-strings-with-entity-framework-5-code-first/
EF will use the name of the database in the connection string. When you want to decouple the name of your connection string from EF, you need to provide your connection string to the constructor. Example:
public class DatabaseContext : DbContext
{
public DatabaseContext()
: base(ApplicationParameters.ConnectionStringName)
{
}
public DatabaseContext(string connectionStringName)
: base(connectionStringName)
{
}
}