I need to consume some .net code from classic ASP, hence I am using com interop.
This works well apart from EF6 and its connection strings. When I try and call the method that uses EF from classic ASP I get
No connection string named 'Entities' could be found in the application config file.
So I thought I would code the connection string into the context with the following:
using (Entities context = new Entities())
{
context.Database.Connection.ConnectionString = #"metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string='data source=server;initial catalog=database;persist security info=True;user id=sa;password=PasswordRemoved;MultipleActiveResultSets=True;App=EntityFramework'";
However, at runtime from my .net test harness, when that method is called, we once again get:
No connection string named 'Entities' could be found in the application config file.
I made sure I specified that I would set the connection string in my code in the entity creation wizard, and subsequently the connection string isn't in my app.config file.
What is stopping EF6.1 from accepting my connection string in code rather than from the config file? Important to note I have scoured SO for solutions and none of them have stuck.
Related
I'm doing my homework, a WCF service that uses SQL Server with Entity Framework, hosted through a console application, and using a WPF client.
There are 3 different projects, and the host and the service is in the same solution. I've included the Entity Framework connection string in the console hosts' app.config file from the web.config file from the service. This way the server and the host throw an exception when I try to make a query:
System.Data.Entity.Core.EntityException: 'The underlying provider failed on Open.'
The inner exception says:
SqlException: An attempt to attach an auto-named database for file C:\Users\username\source\repos\BlogAppWcf\BlogHost\bin\Debug\BlogDb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
So it basically searches for the .mdf file in it's own project folder, while it's inside the service's App_Data folder.
The original connection string looks like this, I copied this to the host's app.config from the web.config:
connectionString="metadata=res://*/BlogDbEntities.csdl|res://*/BlogDbEntities.ssdl|res://*/BlogDbEntities.msl;
provider=System.Data.SqlClient;
provider connection string="
data source=(LocalDB)\MSSQLLocalDB;
attachdbfilename=|DataDirectory|\BlogDb.mdf;
integrated security=True;
MultipleActiveResultSets=True;App=EntityFramework""
I've tried modifying the AttachDbFilename attribute in the app.config, I gave it an absolute path like this:
attachdbfilename=C:\Users\username\source\repos\BlogAppWcf\BlogAppWcf\App_Data\BlogDb.mdf;
and this way it works like a charm! No more exceptions on queries.
But this isn't the right way to do it, especially because I have to send it to my teacher. I want to give it a relative path, just like this:
attachdbfilename=..\..\..\BlogAppWcf\App_Data\BlogDb.mdf;
but it doesn't work this way.
Has anyone got any suggestions, maybe I'm doing or thinking something completely wrong?
According to your description and the issue you encountered, I think the problem boils down to the fact that the attached database is not properly attached to VS built-in database server instance. For this reason, I think we could configure the EntityFramework with VS built-in database instance string.
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MyStore;Integrated
Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
And then override the seed method of the DropCreateDatabaseAlways/DropCreateDatabaseIfModelChanges class to provide the seed data.
Feel free to let me know if there is anything I can help with.
I'm having some trouble getting my Entity Framework connection strings working from my main application and from my class library. Both my main application (an *.exe) and my class library (a COM *.dll that I want to use with Excel) will need to create a connection to either a SQL Server CE database or a SQL Server database.
At the moment, I define two 'base' connection strings in the config file, one for the SQL Server CE implementation and one for the SQL Server implementation. This works fine for my main application, as it reads the appropriate 'base' connection string from the config file (either SQL Server CE or SQL Server), I adjust the connection string value (e.g. file location via 'data source=' for SQL Server CE or database name for SQL Server), and I'm good to go. This however doesn't work well for my class library, as the config file depends on the application that is using the library. I'd like to therefore get rid of my config file dependency completely, by defining my connection strings in code as opposed to in the config file.
The current config file configuration looks as follows:
<add name="ConnectionCE" providerName="System.Data.SqlServerCe.4.0" connectionString="" />
<add name="ConnectionServer" providerName="System.Data.SqlClient" connectionString="" />
I then create the context as follows:
var context = new DbContext("name=ConnectionCE")
//Do things with the context above here, e.g. change the connection string value.
How can I convert the "ConnectionCE" and "ConnectionServer" connection strings so that I don't have to rely on the config file, and can create these directly in my C# code (with the correct provider)?
Thanks!
DbContext(string) constructor accepts name or connection string.
You can simply build the connection string in code and pass it into the constructor.
You can use System.Data.SqlClient.SqlConnectionStringBuilder class to build connection string for SQL Server. I think, for SQL Server CE connection string, it is easy to use string.Format().
The code for SQL Server will look like:
var connStr = new SqlConnectionStringBuilder
{
InitialCatalog = "YourDb",
IntegratedSecurity = true,
DataSource = #".\SQLServer",
};
var db = new DbContext(connStr.ConnectionString);
Provider should be specified for SQL Server CE, so the code will look like next:
var conn = DbProviderFactories.GetFactory("System.Data.SqlServerCe.4.0").CreateConnection();
conn.ConnectionString = "DataSource = \"C:\\ExistingDBFile.db\"";
var db = new DbContext(conn, true);
I am creating a dll project in C# using Visual Studio 2013 .Net 4.5. The project contains an entity model using EF6. My dll will be called as a plugin to an external application, that belongs to a software suite for some hardware products.
I have visual studio set up so that when I press debug it launches this external application (i will refer to as the gateway) which in turn makes calls to my dll, allowing me to debug.
The issue occurs when my dll tries to make calls to the entity model. I get:
InvalidOperationException -- An unhandled exception of type 'System.InvalidOperationException' occured in ENTITYFRAMEWORK.dll
'No connection string named 'Entity' could be found in the application config file.
Now, my config file has, very clearly, the required connection string which was added by VS when I set up the model. I have read all of the similar threads to this issue, and adding the connection string to the config is not the problem.
The gateway does have knowledge of the real DB instance and is given the connection string for that in a configuration. However, the entity connection string and the instance connection string differ, because of the entity jargon that gets added on by VS and EF.
I am able to create a console app which makes calls to my dll, capable of making the enity calls. I had to give the console app a reference to my dll and entity framework as well as add the connection string to the console apps config file.
This has led me to believe that, any app that makes calls into my dll must have knowledge of EF and the connection string.
Is this the case? If so, it would appear to me that I will be unable to use EF for this project because I will have no way to make the gateway aware of EF.
Thanks for your input!
So what I would do in this case is make a new Context which inherits from your current context and in the constructor pass in the connection string.
Alternatively you can also create a connection string that you can then pass into the constructors overload for your context.
public string GetConnectionString()
{
string connectionString = new EntityConnectionStringBuilder
{
Metadata = "res://*/Data.System.csdl|res://*/Data.System.ssdl|res://*/Data.System.msl",
Provider = "System.Data.SqlClient",
ProviderConnectionString = new SqlConnectionStringBuilder
{
InitialCatalog = ConfigurationManager.AppSettings["SystemDBName"],
DataSource = ConfigurationManager.AppSettings["SystemDBServerName"],
IntegratedSecurity = false,
UserID = ConfigurationManager.AppSettings["SystemDBUsername"],
Password = ConfigurationManager.AppSettings["SystemDBPassword"],
MultipleActiveResultSets = true,
}.ConnectionString
}.ConnectionString;
return connectionString;
}
Can't you compose the Entity connectionstring based on the sql connection string?
Otherwhise have a look at this question: How to have DLL specific config file?
Basicly you are supplying a config for the dll file. So besides of myapplication.exe.config you can have a myddl.dll.config
My application is based on entity framework 5, and the connection string is dynamically generated and used in the application. This is working fine. The only problem is if I do not put connection string in app.config file, then it gives an error. That the app.config file should contain the connection string. Is there any way, I can make my process not to find connection string in app.config file. The work around is I can put dummy connection string, but i want it should not look in app.config file for connection string.
Please help. !!
Thanks in advance..
An application does not look at connection strings, it's libraries you use that do that. Luckily your question is tagged with entity-framework, so I guess you somewhere just instantiate a new DbContext(). It would be nice if you could show on what line of code the error occurs.
When you search the web for "entity framework dbcontext pass connection string" and you will find this question which links to the manual somewhere:
public DbContext(string nameOrConnectionString)
So, just supply your valid connection string to the constructor when instantiating your Entity Framework context (not its name, as that again will make it look in the application's configuration).
Thanks CodeCaster for your reply.
I am doing in this way. I have created one class which contains the static method, and in each DAL class i just call this method, and the instance for context is created with the passed connection string.
public static myDBEntities getDBContext(String connectionString) {
myDBEntities DB = new myDBEntities();
DB.Database.Connection.ConnectionString = connectionString;
return DB;
}
My application works fine. There is no issue. I mean it takes the dynamically assigned connection string, But only problem is if I remove the connection string from app.config file, then it gives me error that it expects connection string in app.config. So is there any settings or something, which can lead EDMX not to find connection string in app.config.
Your help will be appreciated. :)
I am trying to fix an app that references a .dll which contains Entity Framework code (.edmx, etc...). I do not have the source so I cannot determine the connection string the edmx file uses. When I run the app I get exceptions that the data source cannot be reached. I have the correct .mdf file that EF is "supposed" to be using, but since I cannot see the connection string, I can't verify this.
Is there another way(tool) to figure out what the connection string is for this dll?
It is quite weird that this 3rd part dll doesn't use a configuration key to get the connection string: entity framework creates a key every time you add a connection.
If the connection is hard-coded you need to use a tool like Reflector to get the connection string
http://reflector.red-gate.com/download.aspx?TreatAsUpdate=1
You can access the following property:
var connStr = Context.Connection.ConnectionString;
This will show you the connection string being used, minus any credentials. The Connection property differs slightly depending upon the version of EF you're using. In EFCF it's:
var connStr = Context.Database.Connection.ConnectionString;