Dynamically creating connection string EF6.0 causes problems - c#

I have the following code somewhere in the application. the code goes like this:
Hyperion.Data.MCQEntities _model = null;
const string K_MODEL = #"res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;";
public Engine(string cnnstr)
{
//string connection =(new ConnectionStringBuilder(cnnstr)).ToString();
string connectionString = new System.Data.EntityClient.EntityConnectionStringBuilder
{
Metadata = K_MODEL, //"res://*",
Provider = "System.Data.SqlClient",
ProviderConnectionString = cnnstr,
}.ConnectionString;
_model = new Data.MCQEntities(connectionString);
_model.Connection.Open();
}
the problem I do not understand is that when I use Metadata = "res://*" it works but when I use Metadata=K_MODEL it does not work at all. what could be the issue?

res//* tells EF that metadata is embedded in the assembly as a resource. If you skip it EF is looking for file on the disk. The default build action for edmx is to embed artifacts in the assembly so if you have not changed this files are not on disk and EF cannot find them.

Related

Activation error occured while trying to get instance of type Database, error occurring only when connection string is created dynamically

I have a piece of code (.NET Framework 4.5.2, Enterprise Library 5.0.505.0) where I need to connect to a SQL Server database. However, the DB name may keep changing depending on user's requirement. So, I have the following piece of code to write the connection string dynamically to the app.config file.
public void CreateNewConnectionStringInConfig(string initialCatalog)
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = ConfigurationManager.AppSettings["Data Source"];
builder.PersistSecurityInfo = true;
builder.InitialCatalog = initialCatalog; //This is the DB name
builder.UserID = ConfigurationManager.AppSettings["User ID"];
builder.Password = ConfigurationManager.AppSettings["Password"];
// Get the application configuration file.
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Create a connection string element.
ConnectionStringSettings csSettings = new ConnectionStringSettings("UserSelectedConnectionString", builder.ConnectionString, "System.Data.SqlClient");
// Get the connection strings section.
ConnectionStringsSection csSection = config.ConnectionStrings;
// Add the new element.
csSection.ConnectionStrings.Add(csSettings);
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
// Refresh the section so the new configuration can be re-read
ConfigurationManager.RefreshSection("connectionStrings");
}
I checked and the connection string is getting created fine in the vshost.exe.Config file while debugging. However, when I am trying to create the Database object, I am getting an error. The code used to create the DB object is as shown below.
public class MyDac
{
private readonly Database _db;
public MyDac()
{
DatabaseProviderFactory factory = new DatabaseProviderFactory();
_db = factory.Create("UserSelectedConnectionString");
}
}
I am getting the following error while trying to create the _db object.
Activation error occured while trying to get instance of type Database, key "UserSelectedConnectionString"
Microsoft.Practices.ServiceLocation.ActivationException: Activation error occured while trying to get instance of type Database, key "UserSelectedConnectionString" ---> Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "Microsoft.Practices.EnterpriseLibrary.Data.Database", name = "UserSelectedConnectionString".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type Database does not have an accessible constructor.
Things that I have tried:
1) Upgrading the Enterprise Library version to 6.0.0.0 resolves the issue but that is not an option for me. I have to keep it to version 5.0.505.0.
2) When I hard code the connection string in the App.config file from before hand (rather than writing it during run time), the app works fine. However, I can't do that in real life because the database name will keep on changing.
Any help will be much appreciated. Thanks!
I changed my code as shown below and that started working. However, I do not have any explanation for it:
public class MyDac
{
private readonly Database _db;
public MyDac()
{
_db = new SqlDatabase("UserSelectedConnectionString");
}
}

How to use a dynamic connection string using a Model First approach but still use the data model in the EDMX?

I have created an EDMX using EF 5 with the Model First approach, i.e. I started with a blank designer and modeled my entities. Now I want to be able to use this model defined in the EDMX but supply runtime SQL Server connection strings without modyfing the config file.
I know how to pass a connection string to the DbContext but the issue is locating the metadata for the mappings within the assembly.
For example, my EDMX has this connection string in the app.config
<add name="MesSystemEntities" connectionString="metadata=res://*/Data.DataContext.EntityFramework.MesSystem.csdl|res://*/Data.DataContext.EntityFramework.MesSystem.ssdl|res://*/Data.DataContext.EntityFramework.MesSystem.msl;provider=System.Data.SqlClient;provider connection string="data source=MyMachine;initial catalog=MesSystem;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
The part that I am missing is the "metadata=res://*/Data.DataContext.EntityFramework.MesSystem.csdl|res://*/Data.DataContext.EntityFramework.MesSystem.ssdl|res://*/Data.DataContext.EntityFramework.MesSystem.msl;"
I want to be able to create a DbContext programmatically passing in a SQL Server connection string but "add on" the metadata portion.
This is what I would like to be generated by the T4 file...
public partial class MesSystemEntities : DbContext
{
public MesSystemEntities()
: base("name=MesSystemEntities")
{
}
public MesSystemEntities(string sqlServerConnectionString)
: base(GetEfConnectionString(sqlServerConnectionString))
{
}
private string GetEfConnectionString(string sqlServerConnectionString)
{
// values added by T4 generation
string format = "metadata=res://*/Data.DataContext.EntityFramework.MesSystem.csdl|res://*/Data.DataContext.EntityFramework.MesSystem.ssdl|res://*/Data.DataContext.EntityFramework.MesSystem.msl;;provider=System.Data.SqlClient;provider connection string=\"{0}\"";
return String.Format(format, sqlServerConnectionString);
}
...
}
My question is how can I get the metadata I need in the T4 generation file to create the Entity Framework connection without hardcoding it for each EDMX file
OR
is there an easier way to load the metadata from the assembly programmatically?
I had the same issue, so instead of relying on all the meta data in the connection string (which I think is not a good idea) I wrote a method to create it from a standard connection string. (I should probably refactor it into an Extension method for DbContext, but this should do)
internal static class ContextConnectionStringBuilder
{
// Modified Version of http://stackoverflow.com/a/2294308/209259
public static string GetEntityConnectionString(string ConnectionString,
Type ContextType)
{
string result = string.Empty;
string prefix = ContextType.Namespace
.Replace(ContextType.Assembly.GetName().Name, "");
if (prefix.Length > 0
&& prefix.StartsWith("."))
{
prefix = prefix.Substring(1, prefix.Length - 1);
}
if (prefix.Length > 1
&& !prefix.EndsWith("."))
{
prefix += ".";
}
EntityConnectionStringBuilder csBuilder =
new EntityConnectionStringBuilder();
csBuilder.Provider = "System.Data.SqlClient";
csBuilder.ProviderConnectionString = ConnectionString.ToString();
csBuilder.Metadata = string.Format("res://{0}/{1}.csdl|"
+ "res://{0}/{1}.ssdl|"
+ "res://{0}/{1}.msl"
, ContextType.Assembly.FullName
, prefix + ContextType.Name);
result = csBuilder.ToString();
return result;
}
}
Basic usage is something like:
string connString =
ConfigurationMananager.ConnectionStrings["name"].ConnectionString;
string dbConnectionString = ContextConnectionStringBuilder(connString,
typeof(MyDbContext));
var dbContext = new MyDbContext(dbConnectionString);

Change Entity model database at runtime

How do I switch the database that my entity model is connected to at runtime?
If I have a training database and a production database, for example, how can I make my application switch between the two by changing a setting in the application.
Justin Pihony has the correct answer.
If you want to access both databases at the same time (switch back and forth) instead of changing config and restarting app.....then you have two settings one for Train and one for Prod then you do your context like so:
string training = ConfigurationManager.ConnectionStrings["Train"].ToString();
string production = ConfigurationManager.ConnectionStrings["Prod"].ToString();
.....
EFContext context = null;
if (InTraining)
context = new EfContext(training);
else
context = new EfContext(production);
Usually this is done by a config file setting. Here is the MSDN on EF connection strings and here is some more info on it, basically saying it should be in your app.config
And, if you want something from the code, here is a code project:
string connectionString = new System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
System.Data.SqlClient.SqlConnectionStringBuilder scsb = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);
EntityConnectionStringBuilder ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/Sample.csdl|res://*/Sample.ssdl|res://*/Sample.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = scsb.ConnectionString;
dataContext = new SampleEntities(ecb.ConnectionString);

Entity Framework: Unable to load the specified metadata resource

I decided to move Entity Connection String from app.config to code. However after setting it up like this:
public static string GetConnectionString() {
string connection = "";
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = dbServer;
sqlBuilder.InitialCatalog = dbInitialCatalog;
sqlBuilder.IntegratedSecurity = false;
sqlBuilder.UserID = dbUserName;
sqlBuilder.Password = dbPasswWord;
sqlBuilder.MultipleActiveResultSets = true;
EntityConnectionStringBuilder entity = new EntityConnectionStringBuilder();
// entity.Name = "EntityBazaCRM";
entity.Metadata = #"res://*/Data.System.csdl|res://*/Data.System.ssdl|res://*/Data.System.msl";
entity.Provider = "System.Data.SqlClient";
entity.ProviderConnectionString = sqlBuilder.ToString();
connection = entity.ToString();
return connection;
}
I have an exception thrown Unable to load the specified metadata resource. in .Designer.cs.
/// <summary>
/// Initialize a new EntityBazaCRM object.
/// </summary>
public EntityBazaCRM(string connectionString) : base(connectionString, "EntityBazaCRM")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
If I define .Name inside my Entity creator it throws another exception
"Other keywords are not allowed when the 'Name' keyword is specified." (System.ArgumentException) Exception Message = "Other keywords are not allowed when the 'Name' keyword is specified.", Exception Type = "System.ArgumentException"
I know I'm missing something that I have to change so that self generated code uses new connection string but where to look for it?
After reading this answers article and this blog I changed:
entity.Metadata = #"res://*/Data.System.csdl|res://*/Data.System.ssdl|res://*/Data.System.msl";
To:
entity.Metadata = "res://*/";
And it works :-)
I upgraded to the new csproj format(Visual studio 2017 with simple format) after that I started getting this error. The csproj has a feature where you don't need to include each file instead it includes all the relevant files under the folder by default so the entity framework files are treated same way so those are not embedded into the assembly by default.
I need to go and manually change the build action of my edml file(edmx in case of Microsoft entity framework) to 'DevartEntityDeploy' (I hope it is EntityDeploy for Microsoft Entity framework)and build it which solved my problem

How to in-code supply the password to a connection string in an ADO.Net Entity Data Model

I've been following this tutorial on how to create an OData service.
http://www.hanselman.com/blog/CreatingAnODataAPIForStackOverflowIncludingXMLAndJSONIn30Minutes.aspx
And it works flawlessly ... but, in the Entity Data Model Wizard, when it asks you to "Choose Your Data Connection" it gives you this warning.
"This connection string appears to contain sensitive data (for example, a password) that is required to connect to the database. Storing sensitive data in the connection string can be a security risk. Do you want to include this sensitive data in the connection string?"
If I choose: "No, exclude sensitive data from the connection string. I will set it in my application code."
I do not see where I can, "in my application code" insert the password. (My company stores them encrypted in the registry)
Plus, I have multiple DBs that I need to connect to, depending on the environment (Dev, CA, or Prod) and I need to know what DB is referenced in the connection string to get the correct password.
Thanks.
When you create your context, you can set a connection string. To build this connection string, you can parse the connection string without the password with an EntityConnectionStringBuilder and then parse the inner connection string with an other ConnectionStringBuilder, depending on your browser. Then you can set the password and pass it to the constructor.
var originalConnectionString = ConfigurationManager.ConnectionStrings["your_connection_string"].ConnectionString;
var entityBuilder = new EntityConnectionStringBuilder(originalConnectionString);
var factory = DbProviderFactories.GetFactory(entityBuilder.Provider);
var providerBuilder = factory.CreateConnectionStringBuilder();
providerBuilder.ConnectionString = entityBuilder.ProviderConnectionString;
providerBuilder.Add("Password", "Password123");
entityBuilder.ProviderConnectionString = providerBuilder.ToString();
using (var context = new YourContext(entityBuilder.ToString()))
{
// TODO
}
I added a "dummy" password in the configuration file ("XXXXX"), then replaced that value with the real password in the entity constructor
public MyDatabaseContainer() : base("name=MyDatabaseContainer")
{
Database.Connection.ConnectionString = Database.Connection.ConnectionString.Replace("XXXXX","realpwd");
}
Modify the constructor of the entities
public sampleDBEntities() : base("name=sampleDBEntities")
{
this.Database.Connection.ConnectionString = #"Data Source=.\;Initial Catalog=sampleDB;Persist Security Info=True;User ID=sa;Password=Password123"; ;
}
My sample application was written in "Database First" mode and the "CreateNewConnectionString" method below works just fine (though it doesn't look all that elegant.)
The "CreateNewConnectionString2" method looks really elegant, BUT causes an exception telling me it's only valid in "Code First" mode.
So I'm providing both methods along with the constructor I modified to use my methods. NOTE AND BEWARE, I've modified code generated by a template and that is subject to being overwritten if the code is regenerated. To me it seems like the right place to put it.
If your application was generated in "Code First" mode, you may need to use "CreateNewConnectionString2" (I have not yet tested this option.)
I hasten to admit that I copied both code blocs from other postings as I don't yet know nearly enough about all this to write my own code.
private static string CreateNewConnectionString(string connectionName, string password)
{
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~").ConnectionStrings.ConnectionStrings[connectionName];
//or:
//var config = ConfigurationManager.ConnectionStrings[connectionName];
var split = config.ConnectionString.Split(Convert.ToChar(";"));
var sb = new System.Text.StringBuilder();
for (var i = 0; i <= (split.Length - 1); i++)
{
if (split[i].ToLower().Contains("user id"))
{
split[i] += ";Password=" + password;
}
if (i < (split.Length - 1))
{
sb.AppendFormat("{0};", split[i]);
}
else
{
sb.Append(split[i]);
}
}
return sb.ToString();
}
private static string CreateNewConnectionString2(string connectionName, string password)
{
var originalConnectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
var entityBuilder = new EntityConnectionStringBuilder(originalConnectionString);
var factory = DbProviderFactories.GetFactory(entityBuilder.Provider);
var providerBuilder = factory.CreateConnectionStringBuilder();
providerBuilder.ConnectionString = entityBuilder.ProviderConnectionString;
providerBuilder.Add("Password", password);
entityBuilder.ProviderConnectionString = providerBuilder.ToString();
return entityBuilder.ProviderConnectionString;
}
public ChineseStudyEntities()
: base(CreateNewConnectionString("ChineseStudyEntities", "put YOUR password here")) // base("name=ChineseStudyEntities")
{
}

Categories

Resources