Monday, 11 December 2017

How to specify database name in Code First?

How to Use a Different Connection String Name with EF

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)
    {
    }

}

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>  

No comments:

Post a Comment

Note: only a member of this blog may post a comment.