I have a context that derives from DbContext like the one below:
public class StudentContext : DbContext
{
public StudentContext(string connectionString) : base(connectionString)
{
}
protected override void OnModelCreating(DBModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<StudentContext, StudentMigrations.Configuration>());
}
public DbSet<Students> Students {get; set;}
}
I'm trying to pass the connection string by:
studentContext = new StudentContext(settings.ConnectionString)
The settings are loaded at run-time by reading a configuration file. I've tried this and I've also tried setting the connection string inside the StudentContext constructor by using this.Database.Connection.ConnectionString.In either case, I get an exception that asks me to provide a default constructor or provide an implementation of IDbContextFactory. The only thing that works is this:
public class StudentContext : DbContext
{
public static string ConnectionString;
public StudentContext(string connectionString) : base(ConnectionString = connectionString)
{
}
//And also provide a default implementation of the DbContext constructor:
public StudentContext() : base(ConnectionString)
{
}
protected override void OnModelCreating(DBModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<StudentContext, StudentMigrations.Configuration>());
}
public DbSet<Students> Students {get; set;}
}
I am trying to reduce the use of statics in code and therefore, if I could get the first option to work, that'd be great.