Answer the question
In order to leave comments, you need to log in
How to organize database selection when using Entity Framework?
I am writing an application in C# using the Entity Framework. There are several databases with an identical table structure, and when starting the application, you need to ask the user which database he wants to connect to. I can not find a way how to organize this, tk. when creating a *.edmx model through the wizard, I have a completely defined connection string. Of course, you can make your own model for each database, but perhaps there is a way, based on one model, to organize a connection to the database selected by the user?
I use:
Visual studio 2013
Entity Framework 6.0
MS SQL Server 2008
Answer the question
In order to leave comments, you need to log in
There is a ChangeDatabase method Tyts
from
an already live DB context'a you can get:
context.Database.Connection.ChangeDatabase(databaseName);
Who prevents you from putting the connection string into an external configuration and choosing at startup, as is done in 1C, for example?
The answer to the question is in the previous comment.
private static void InitConnectSetting() {
Configuration config = ConfigurationManager.
OpenExeConfiguration(ConfigurationUserLevel.None);
var path = DebugMode ? DebugModeDbPath() : Application.StartupPath;
Dictionary<string, string> db = new Dictionary<string, string>() {
{"ec", string.Format("{0}\\db\\{1}", path, /*DebugMode ? "data.db" : */"data.db")},
};
var conSets = config.ConnectionStrings;
foreach (var key in db.Keys) {
var sName = key + "Entities";
var conSet = conSets.ConnectionStrings[sName];
if (conSet != null)
conSets.ConnectionStrings.Remove(conSet);
conSet = new ConnectionStringSettings();
conSet.ProviderName = "System.Data.EntityClient";
conSet.Name = sName;
conSet.ConnectionString =
string.Format("metadata=res://*/{0}Model.csdl|res://*/{0}Model.ssdl|res://*/{0}Model.msl;" +
"provider=System.Data.SQLite;" +
"provider connection string=\"data source={1}\"", key, db[key]);
conSets.ConnectionStrings.Add(conSet);
var file = new FileInfo(db[key]);
if (false && !file.Exists) {
using (BinaryWriter binWriter =
new BinaryWriter(File.Open(db[key], FileMode.Create))) {
switch (key) {
case "ec":
binWriter.Write(Properties.Resources.kladr, 0, Properties.Resources.kladr.Length);
break;
}
}
}
}
conSets.SectionInformation.ForceSave = true;
conSets.SectionInformation.RequirePermission = false;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(conSets.SectionInformation.Name);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question