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
Related
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");
}
}
I am writing a test library that needs to traverse the Entity Framework MetadataWorkspace for a given DbContext type. However, as this is a test library I would rather not have a connection to the database - it introduces dependencies that may not be available from the test environment.
When I try to get a reference to the MetadataWorkspace like so:
var metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;
I get a SqlException:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Is it possible to do what I want without a connection string?
Yes you can do this by feeding context a dummy connection string. Note that usually when you call parameterless constructor of DbContext, it will look for connection string with the name of your context class in app.config file of main application. If that is the case and you cannot change this behavior (like you don't own the source code of context in question) - you will have to update app.config with that dummy conneciton string (can be done in runtime too). If you can call DbContext constructor with connection string, then:
var cs = String.Format("metadata=res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl;provider=System.Data.SqlClient;provider connection string=\"\"", "TestModel");
using (var ctx = new TestDBEntities(cs)) {
var metadata = ((IObjectContextAdapter)ctx).ObjectContext.MetadataWorkspace;
// no throw here
Console.WriteLine(metadata);
}
So you providing only parameters important to obtain metadata workspace, and providing empty connection string.
UPDATE: after more thought, you don't need to use such hacks and instantiate context at all.
public static MetadataWorkspace GetMetadataWorkspaceOf<T>(string modelName) where T:DbContext {
return new MetadataWorkspace(new[] { $"res://*/{modelName}.csdl", $"res://*/{modelName}.ssdl", $"res://*/{modelName}.msl" }, new[] {typeof(T).Assembly});
}
Here you just use constructor of MetadataWorkspace class directly, passing it paths to target metadata elements and also assembly to inspect. Note that this method makes some assumptions: that metadata artifacts are embedded into resources (usually they are, but can be external, or embedded under another paths) and that everything needed is in the same assembly as Context class itself (you might in theory have context in one assembly and entity classes in another, or something). But I hope you get the idea.
UPDATE2: to get metadata workspace of code-first model is somewhat more complicated, because edmx file for that model is generated at runtime. Where and how it is generated is implementation detail. However, you can still get metadata workspace with some efforts:
public static MetadataWorkspace GetMetadataWorkspaceOfCodeFirst<T>() where T : DbContext {
// require constructor which accepts connection string
var constructor = typeof (T).GetConstructor(new[] {typeof (string)});
if (constructor == null)
throw new Exception("Constructor with one string argument is required.");
// pass dummy connection string to it. You cannot pass empty one, so use some parameters there
var ctx = (DbContext) constructor.Invoke(new object[] {"App=EntityFramework"});
try {
var ms = new MemoryStream();
var writer = new XmlTextWriter(ms, Encoding.UTF8);
// here is first catch - generate edmx file yourself and save to xml document
EdmxWriter.WriteEdmx(ctx, writer);
ms.Seek(0, SeekOrigin.Begin);
var rawEdmx = XDocument.Load(ms);
// now we are crude-parsing edmx to get to the elements we need
var runtime = rawEdmx.Root.Elements().First(c => c.Name.LocalName == "Runtime");
var cModel = runtime.Elements().First(c => c.Name.LocalName == "ConceptualModels").Elements().First();
var sModel = runtime.Elements().First(c => c.Name.LocalName == "StorageModels").Elements().First();
var mModel = runtime.Elements().First(c => c.Name.LocalName == "Mappings").Elements().First();
// now we build a list of stuff needed for constructor of MetadataWorkspace
var cItems = new EdmItemCollection(new[] {XmlReader.Create(new StringReader(cModel.ToString()))});
var sItems = new StoreItemCollection(new[] {XmlReader.Create(new StringReader(sModel.ToString()))});
var mItems = new StorageMappingItemCollection(cItems, sItems, new[] {XmlReader.Create(new StringReader(mModel.ToString()))});
// and done
return new MetadataWorkspace(() => cItems, () => sItems, () => mItems);
}
finally {
ctx.Dispose();
}
}
The solution proposed by Evk did not work for me as EdmxWriter.WriteEdmx would eventually connect to the database.
Here is how I solved this:
var dbContextType = typeof(MyDbContext);
var dbContextInfo = new DbContextInfo(dbContextType, new DbProviderInfo(providerInvariantName: "System.Data.SqlClient", providerManifestToken: "2008"));
using (var context = dbContextInfo.CreateInstance() ?? throw new Exception($"Failed to create an instance of {dbContextType}. Does it have a default constructor?"))
{
var workspace = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;
// ... use the workspace ...
}
By creating the context this way, Entity Framework does not try to connect to the database when accessing the ObjectContext property.
Note that your DbContext class must have a default constructor for this solution to work.
Like the title. How can I do it?
I tried something, but it doesn't work like I was expecting.
I'm using an Entity Framework model. I need to pass my connection string like parameter, so, in another file, I've written
namespace MyNamespace.Model
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class MyEntities: DbContext
{
public MyEntities(string nameOrConnectionString) : base(nameOrConnectionString)
{
}
}
}
When I startup the app, I call this constructor in this way, so I can refer to this from anyway in the app:
public static MyEntities dbContext = new MyEntities(mdlImpostazioni.SetConnectionString());
where mdlImpostazioni.SetConnectionString() returns a string (the data are correct):
server=192.168.1.100\SVILUPPO;database=MyDB;uid=myName;pwd=111111;
When I execute this code, it seems to be all ok, but when I try to make a query like:
var query = (from r in MainWindow.dbContext.TabTipoSistema select r);
it throws an exception from here:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException(); //exception here
}
So, this is a bad way... which is the right one? (using only code C#, not from xaml)
Your approach is correct, but you need to remember the connection string for EF requires the metadata and so on. So use the EntityConnectionStringBuilder. For example:
// the model name in the app.config connection string (any model name - Model1?)
private static string GetConnectionString(string model, YourSettings settings)
{
// Build the provider connection string with configurable settings
var providerSB = new SqlConnectionStringBuilder
{
// You can also pass the sql connection string as a parameter instead of settings
InitialCatalog = settings.InitialCatalog,
DataSource = settings.DataSource,
UserID = settings.User,
Password = settings.Password
};
var efConnection = new EntityConnectionStringBuilder();
// or the config file based connection without provider connection string
// var efConnection = new EntityConnectionStringBuilder(#"metadata=res://*/model1.csdl|res://*/model1.ssdl|res://*/model1.msl;provider=System.Data.SqlClient;");
efConnection.Provider = "System.Data.SqlClient";
efConnection.ProviderConnectionString = providerSB.ConnectionString;
// based on whether you choose to supply the app.config connection string to the constructor
efConnection.Metadata = string.Format("res://*/Model.{0}.csdl|res://*/Model.{0}.ssdl|res://*/Model.{0}.msl", model); ;
return efConnection.ToString();
}
// Or just pass the connection string
private static string GetConnectionString(string model, string providerConnectionString)
{
var efConnection = new EntityConnectionStringBuilder();
// or the config file based connection without provider connection string
// var efConnection = new EntityConnectionStringBuilder(#"metadata=res://*/model1.csdl|res://*/model1.ssdl|res://*/model1.msl;provider=System.Data.SqlClient;");
efConnection.Provider = "System.Data.SqlClient";
efConnection.ProviderConnectionString = providerConnectionString;
// based on whether you choose to supply the app.config connection string to the constructor
efConnection.Metadata = string.Format("res://*/Model.{0}.csdl|res://*/Model.{0}.ssdl|res://*/Model.{0}.msl", model);
// Make sure the "res://*/..." matches what's already in your config file.
return efConnection.ToString();
}
EDIT
The exception you get is because when you pass a pure SQL connection string, it assumes you are working with Code first, so it calls the OnModelCreation event. When you include the MetaData section as shown above, that tells EF it's a complete EF connection string.
I believe the problem lies on the Datasource you specify. You need to add the port of the connection, e.g if your SQL Server is configured on Port 1433, try:
server=192.168.1.100,1433\SVILUPPO;database=MyDB;uid=myName;pwd=111111;
more details about connection strings you can find Here
Also I am not sure if uid and pwd are valid, better try User ID and Password:
Server=192.168.1.100,1433\SVILUPPO;Database=MyDB;User ID=myName;Password=111111;
Finally mind the case sensitivity.
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.
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);