I have inherited an application which is using Entity Framework to access a SQL Server database. The DbContext class has the constructor as shown below, where BuildingPermits is the name of the initial catalog.
I would like to be able to switch between databases (with the same connection) via a config file instead of changing the code.
How can I accomplish this?
public BuildingPermitsDbContext() : base("BuildingPermits")
{
Database.SetInitializer<BuildingPermitsDbContext>(null);
}
You can try this.
using System.Configuration;
public BuildingPermitsDbContext() : base(DatabaseName())
{
Database.SetInitializer<BuildingPermitsDbContext>(null);
}
private static string DatabaseName()
{
var db = ConfigurationManager.AppSettingss["desiredDbName"];
return db;
}
Related
I know that the default return here is the SQL Server database type, but I need the MySQL database type, the problem is to create a DbContext instance of the specified database type?
Of course, I know that it can also be created by specifying the connectionName, but the database connection string is encrypted and the string needs to be decrypted
The pseudo code is as follows:
public partial class MyDbContext : DbContext
{
static string mysqlConn = ReadConnectionString(); //Get the encrypted MySQL connection string
public MyDbContext() : base(mysqlConn)
{
// Even if I want to modify the connection string in this way, nor will it throw a connection string malformed exception
Database.Connection.ConnectionString = DecryptConnectionString(mysqlConn);
}
}
Ok, it's about what I expected, few of my questions can be answered.
Although I am not too familiar with EntityFramework, by looking at the source code of DbContext, I can almost certainly determine that this is a design flaw, it lacks a constructor like this:
Public DbContext(string connectionString, string providerName)
I had same problem and found .Net framework 4.5 needs additional attribute on DbContext class to use MySql as below
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class MySqlContext : DbContext
{
...
}
I have this inicializer in my project:
public class MyInitializer : CreateDatabaseIfNotExists<AppDbContext>
I have also deployed an application in Azure with SQL database.
I would like to clear the whole DB and reseed it with my initializer. How can I do it please?
You can create your custom initializer
public class MyCustomInitializer : IDatabaseInitializer<AppDbContext>
{
public void InitializeDatabase(AppDbContext context)
{
if (context.Database.Exists())
{
context.Database.Delete();
}
context.Database.Create();
// populate data
}
}
I found out that the only possible option is to manually delete my DB, then create new DB with same name (so the same connection string) and that's it.
The requirement is to execute a sql query using DbContext (EF 5 in DatabaseFirst mode) at the beginning of every Oracle session that DbContext might invoke.
Putting this in the constructor gives inconsistent results because there are instances where this sql query is not run at all when expected.
The setup is EF5 in DBFirst mode connecting to Oracle10gR2 using ODP.NET v12 Managed driver.
public partial class MyContext : DbContext
{
public MyContext(string connectionString)
: base(connectionString)
{
Database.ExecuteSqlCommand(Constants.SqlQuery);
}
}
I instantiate the context by passing the connecting string because the connection string needs to be dynamic as follows:
using(var context = new MyContext(GetConnectionString()))
{
...
...
context.SaveChanges();
}
Is there a way to ensure that this query is always run whenever an Oracle session is created?
You can extend the DbContext class and implement each method to do so. For example....
public KashDbContext : DbContext
{
public int SaveChanges()
{
Database.ExecuteSqlCommand(Constants.SqlQuery);
base.SaveChanges();
}
//Do for all methods
}
Just implement the OnContextCreated() method in your partial class:
partial void OnContextCreated()
{
this.ExecuteStoreCommand(Constants.SqlQuery, new object[] { });
}
I've spent a while on this now and have only found a workaround solution that I'd rather not do...
I have a context as shown below. Is there a programmatic way to specify the database to connect to via the constructor, and get it to use the System.Data.SQLite entity framework provider to connect to a SQLite database? This is working via the app.config (with a connectionstring called "Context"), but not via any programmatic way I can find of supplying it. I have tried using an entity connectionstring builder and that produces the following string:
provider=System.Data.SQLite;provider connection string='data
source="datafile.db"'
When the context is first queried with this string I get a message "Keyword not supported: 'provider'."
public class Context : DbContext
{
public IDbSet<Test> Tests { get; set; }
public Context()
: base("Context")
{
}
}
*Edit.
I may have solved this by implementing my own connectionfactory:
public class ConnectionFactory : IDbConnectionFactory
{
public DbConnection CreateConnection(string nameOrConnectionString)
{
return new SQLiteConnection(nameOrConnectionString);
}
}
Then setting:
Database.DefaultConnectionFactory = new ConnectionFactory();
However, it seems like there should be a built in way to do this, and also one that does not involve overriding the global default connection factory.
I used SQL Server CE 4.0 in my windows app and use Entity Framework to create a model of it.
It works fine but my problems is that it doesn't have a constructor to change the connection string, and by default it reads the connection string from the app.config file.
using (var Context = new MyEntitiesModel(//has no constructor))
{
...
}
I create a dynamic connection string and
using (var Context = new MyEntitiesModel())
{
Context.Database.Connection.ConnectionString = entityConnection.ConnectionString;
}
It works fine by this way but if I remove another connection string in app.config file it gave me this.
error = invalid metasource ....
because the default constructor uses it
How can I handle it?
Create your own constructor. MyEntitiesModel is partial class you can add your own partial part of the class and add constructor accepting a connection string.
public partial class MyEntitiesModel {
public MyEntitiesModel(string connectionString) : base(connectionString) { }
}
Im using DbContext. There are several Overload Constructors eg:
ObjectContext also has a similar set of constructor overloads.
System.Data.Entity DbContext example
Context = new BosMasterEntities(nameOrConnectionString: nameOrConnectionString);
You can connect to multiple Dbs at same time.