No connection string named could be found in the application config file - c#

I'm using EF and generated .EDMX from it but then I only wanted it to be used for automated generation of Class Files.
I then used the Class Files to create a Entity Model and then created a DB Context and then Repository. I'm calling a WebApi (which is in a separate project but same solution) to access the repository to GET data. While I run the WebApi, I'm getting the error,
{"No connection string named 'DBEntities' could be found in the application config file."}
But within my DAL, I have a webConfig and that has the following entry so I'm not quite sure what has gone wrong,
add name="DBEntities" connectionString="metadata=res://*/Models.DBModel.csdl|res://*/Models.DBModel.ssdl|res://*/Models.DBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MY-PC;initial catalog=DB;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient"

In the DBContext file, remove
public RaficaDB()
: base("name=DefaultConnection"){}
to
public RaficaDB()
: base("DefaultConnection"){}
EF 4.3, EF 5 and EF 6 do not like the connection string being called name=xxxxx
Answer found here -> No connection string named 'MyApplicationEntities' could be found in the application config file

You say "within my DAL, I have a webConfig". I guess the connection string is in the configuration file of a referenced class library, but not in the main configuration file you have in your entry project (a web api project, I guess looking at the tags).
If so, just copy the connection string in the entry project configuration file.

Insert following section in the configuration section of the .config file of the same project where your .edmx file is under.
You may also create different connection string for different environment in the .config file of the main project and pass any of the connection string as parameter of the constructor of the DBContext.
<connectionStrings>
<add name="DBEntities" connectionString="metadata=res://*/Models.DBModel.csdl|res://*/Models.DBModel.ssdl|res://*/Models.DBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MY-PC;initial catalog=DB;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>

Setting the project as Startup project worked for me

I found that this worked:
1) Check if you have several "App.config" files.
2) Check if has a wrong name than the connection string it has to use.
3) Save the project and run the program
It should work now.

Copy and paste the connectionstring to your WEBAPI Project web.config file will solve the issue.

It's dumb, but I had this error that was fixed by a Rebuild All !!
Might as well have turned it off and on again....

If none of the above fixes the issue, then probably you are doing the mistake I did, here was my case:
I have multiple projects in my solution and the Startup project was different than the one having the entity framework, switching project from the package manager console seems like a buggy thing especially in entity framework commands, so here what I did:
Set your webapi(Or the project has the entity framework) as a startup project.
Rebuild the solution and try again.
Run the entity framework command again.
If the above doesn't work then try to close the solution and try from Step 2, this should fix it.

The easiest solution:
Remove current edmx file and related connection string in app.config
and add Edmx item with same name as previous again.
this worked for me.

Related

Update-Database Always updating in .\SQLEXPRESS, in Entity Framework

I have a solution project in in which I have implemented Entity framework in a class library Project.
I have a App.config file in the same class library in which I am giving my connection string as
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=DDC5-D-4R03T72;Initial Catalog=ServiceAdaptor;User ID=sa;Password=pwd;MultipleActiveResultSets=True;Integrated Security=False"
providerName="System.Data.SqlClient"/>
</connectionStrings>
(I am using Visual Studio 2010, and I am using Code-First Approach EF)
Now the problem is when I run command "Update-Database -Verbose",
It is not creating tables in above DB , rather it creates in .\SQLExpress which I didn't mentioned in anywhere in my soln)
when I gave command like
Update-Database -Verbose -ConnectionStringName "DefaultConnection"
it gave me message
"No connection string named 'DefaultConnection' could be found in the
application config file."
What I conclude is my Update-Database command is not able to get the connection string from config file.
Not able to figure out,What is wrong.
Finally I found the solution, There Problem was here that somehow Update-database command was searching Connection string in Web.Config file not in App.Config file as in my Case I have Class library project which has App.config file.
Since It did't get the Connection string By default EF framework in VS 10 will assume .\SQLEXPRESS as default db and create the tables there.
So the solution I found is:
1) Add reference System.Configuration in the project
2) Insteed of using base("DefaultConnection") in dbContext use as below
base(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)

Error : No connection string in application config file... but there is one

I have the following error when I try to build my solution:
No connection string named 'TechnicalAnalyzerEntities' could be found
in the application config file.
The thing is that :
1/ there is one :
<connectionStrings>
<add name="TechnicalAnalyzerEntities" connectionString="metadata=res://*/Data.Database.TAdb.csdl|res://*/Data.Database.TAdb.ssdl|res://*/Data.Database.TAdb.msl;provider=System.Data.SqlClient;provider connection string="data source=PSYKOTROPYK-PC\PSYKOTROPYK;initial catalog=TechnicalAnalyzer;persist security info=True;user id=***;password=***;network library=dbnmpntw;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
2/ there is just one project in my solution (I search and the same error seems to appear when people have one project with the connection string and a startup project without, well not my case)
3/ this error seems not to prevent my project to run, nor Entity Framework to access the data and bind it to my treeview.
Actually the only issue is that there is this error showing in my error list and the MainWindow.xaml file (where the error is referenced) that can't show properly the custom control that then needs this connection string ==> cannot create an instance of "TreeviewSelector". The thing is that the custom control xaml file (TreeviewSelector.xaml as you guessed) is properly shown in the xaml editor.
This is not a dramatic error that prevents me to go forward on my project, but it is annoying to have errors and not to be able to properly use the xaml editor.
N.B.: A few other point that may be of interest :
1/ I use Entity Framework 6.0
2/ The project is on my laptop and the database on my desktop
3/ Blend shows the same MainWindow.xaml error
4/ If I put a copy of my project on my desktop (so on the same system as my database) I have the same problem
I've been there and struggled with that exact issue.
The solution is to add Entity Framework 6 to your application using NuGet. This will auto generate the correct connection string for you, and automatically set up your app.config perfectly.
The NuGet wizard that sets up app.config is quite smart: if there are some bad settings in it already, it will remove them and add good entries.
See my answer here: Upgrade from Entity Framework 5 to 6.
Try reordering the sections in your app.config file. Sometimes, if the sections are in an unexpected order, they will generate a schema error on compile.
Base the ordering of the sections on a freshly generated app.config file using the wizards in Visual Studio for Entity Framework.
Try closing all of the open files in your solution by pressing Ctrl-F4 repeatedly. Sometimes, this will clear any rogue errors generated at compile time.
There is a known bug in visual studio where xml files with an unexpected schema creates benign errors during a compile.

Not using database connection string

I have google'd the crap out of this problem, I cannot find a solution.
Using EF code first approach against a domain assembly, being consumed by a .net web application.
in the domain project there is a app.config, in there I have the following connection string for EF
<connectionStrings>
<add name="DefaultConnection" connectionString="Initial Catalog=easyDayTea;Data Source=localhost;user=sa; password=12344321" providerName="System.Data.SqlClient" />
Then in the context class TeaDb.cs I have the following constructor:
public TeaDb()
: base("name=DefaultConnection")
{
}
I have also tried just using "DefaultConnection" by itself in the constructor.
The problem:
Everything was fine until EF decided it wasn't going to take notice of additional classes/tables added to the context, so I removed EF from the project by deleting the migrations folder and empting the database of tables, then re ran enable-migrations and then the web application project to make EF do it's stuff to the database. However it did nothing!
When I run the web application though it works! and there is data (from the seed) in the tables, however not in any database i can see! It must be using a portable sql file, which doesn't make sense as I have it configured for a specific database / server by use of the configuration string.
I have also tried specifically specifying the connection string to use by doing a:
update-database -ConnectionStringName DefaultConnection -f
Still no joy.
If anyone could help me it would be amazing!
Thanks,
Xavier.
You'll find your database at Users\[youruser]\[Name you passed in your context constructor].mdf
app/web.config are only used if they are in the main project, if you have an app.config/web.config outside your main project it will not be used (some templates add them, but they are meant to be used as an example).
Check this answer for a similar problem with EF4
EF doesn't use the connection string from the app.config in the class library. It will use the connection string from the web.config in your web application. If you don't have the connection string defined in your web.config then it might be using conventions to attach the database with LocalDb in your App_Data directory.

No connection string named 'MyEntities' could be found in the application config file

I am using entity framework and ASP.NET MVC 4 to build an application
My solution is split into two projects;
A class library that includes my data model (.edmx) file and a few custom interfaces
The 'container' MVC project that references the class library above
My problem is that when I attempt to use the 'MyEntites' DbContext I get the the following error:
No connection string named 'MyEntities' could be found in the
application config file.
I guess the problem has something to do with the fact that connection string lies within the app.config of the class library rather than the MVC project.
Does anyone have any suggestions?
Try copying the connections string to the .config file in the MVC project.
You are right, this happens because the class library (where the .edmx file) is not your startup / main project.
You'll need to copy the connection string to the main project config file.
Incase your startup / main project does not have a config file (like it was in my Console Application case) just add one (Startup project - Add New Item -> Application Configuration File).
More relevant information can be found here:
MetadataException: Unable to load the specified metadata resource
make sure that you make your project (with the DbContext) as startup
OR
Add to the project that is set as startup your connection string in the app.config (or web.config)
OR
Call the command like this
Update-Database -Script -ProjectName '<project name>' -StartupProjectName '<project name>' -ConnectionString 'data source=.;initial catalog=<db name>;integrated security=True;MultipleActiveResultSets=True' -ConnectionProviderName 'System.Data.SqlClient'
Then try again
You could just pass the connection string to EntityFramework and get on with your life:
public partial class UtilityContext : DbContext
{
static UtilityContext()
{
Database.SetInitializer<UtilityContext>(null);
}
public UtilityContext()
: base("Data Source=SERVER;Initial Catalog=DATABASE;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD;MultipleActiveResultSets=True")
{
}
// DbSet, OnModelCreating, etc...
}
copy connection string to app.config or web.config file in the project which has set to "Set as StartUp Project" and if in the case of using entity framework in data layer project - please install entity framework nuget in main project.
As you surmise, it is to do with the connection string being in app.config of the class library.
Copy the entry from the class app.config to the container's app.config or web.config file
If you have multiple projects in solution, then setUp project as started where you have your truth App.config.
Add an App.Config file
Set the project as startup project.
Make sure you add the connection strings after entityFramework section:
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</configSections>
<connectionStrings>
<!-- your connection string goes here, after configSection -->
</connectionString>
It is because your context class is being inherited from DbContext. I guess your ctor is like this:
public MyEntities()
: base("name=MyEntities")
name=... should be changed to your connectionString's name
It also happens if the startup project is changed to the one, which does not have the connection strings.
Right Click Solution - click properties
Under Common Properties,select startup project
On the right pane select the project which
has the connection strings (in most cases, it will be MVC projects -
the project that starts the solution)
Yeah, it's silly. You can avoid copying the connection string by using a connection builder. VB.Net code (used in production, but slightly modified here, so treat as untested, happy to assist with any issues), where I have a serverName variable, a databaseName variable, I pass them into a method and have it generate the connection for me:
Dim EfBuilder As New System.Data.EntityClient.EntityConnectionStringBuilder("metadata=res://*/VMware.VmEf.csdl|res://*/VMware.VmEf.ssdl|res://*/VMware.VmEf.msl;provider=System.Data.SqlClient;provider connection string=""data source=none;initial catalog=none;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""")
Dim SqlBuilder As New Data.SqlClient.SqlConnectionStringBuilder(EfBuilder.ProviderConnectionString)
SqlBuilder.DataSource = serverName
SqlBuilder.InitialCatalog = databaseName
EfBuilder.ProviderConnectionString = SqlBuilder.ConnectionString
Using vmCtx As New VmEfConn(EfBuilder.ConnectionString)
are you using more than one project on your solution?
Because if you are, the web config you must check is the one on the same project as de .edmx file
Add ConnectionString to MVC Project Web.config file
I've had this problem when I use multiple proyects, the start proyect with web.config and app.config for EntityFramework project.
for avoid this problem you must:
You need the connection string in the started *.config file.
You need have installed the EntityFramework DLL into your references
I have faced the same issue. I was missed to put connection string to startup project as I am performing data access operation from other layer. also if you don't have app.config in your startup project then add app.config file and then add a connection string to that config file.
I got this by not having the project set as startup, as indicated by another answer. My contribution to this - when doing Add-Migrations and Update-Database, specify the startup project as part of the command in Nuget Package Manager Console (do not include the '[' or ']' characters, that's just to show you that you need to change the text located there to your project name):
Enable-Migrations
Add-Migrations -StartupProject [your project name that contains the data context class]
Update-Database -StartupProject [same project name as above]
That should do it.
The connection string generated by the project containing the .edmx file generates the connection string, this would appear to be a holdover from the app.config sorts of files that were copied to the output directory and referenced by the executable to store runtime config information.
This breaks in the web project as there is no automatic process to add random .config information into the web.config file for the web project.
Easiest is to copy the connection string from the config file to the connections section of the web.config file and disregard the config file contents.
The best way I just found to address this is to temporarily set that project (most likely a class library) to the startup project. This forces the package manager console to use that project as it's config source. part of the reason it is set up this way is because of the top down model that th econfig files usually follow. The rule of thumb is that the project that is closest to the client (MVC application for instance) is the web.config or app.config that will be used.
Make sure you've placed the connection string in the startup project's ROOT web.config.
I know I'm kinda stating the obvious here, but it happened to me too - though I already HAD the connection string in my MVC project's Web.Config (the .edmx file was placed at a different, class library project) and I couldn't figure out why I keep getting an exception...
Long story short, I copied the connection string to the Views\Web.Config by mistake, in a strange combination of tiredness and not-scrolling-to-the-bottom-of-the-solution-explorer scenario.
Yeah, these things happen to veteran developers as well :)
This problem happen when you are using Layers in your Project and defined or install Entity frame work in DataLayer and try to run your Project
So to overcome from this problem copy the connection string from the layer where the Edmx file is there and paste the connection string in main web.config.
Add a connection string in the root web.config file of 'container' MVC project that references the class library as following:
<connectionStrings>
<add name="MyEntities" connectionString="complete connection string here" providerName="System.Data.SqlClient" />
</connectionStrings>
If you do not want to use "MyEntities" as connection name then change it as you wish but make the following change in your MyEntities DbContext class:
MyEntities: DbContext
{
public MyEntities():base("Name-Of-connection-string-you wish to connect"){ }
}
Reason for this error is, If we will not specify the name of connection string Or connect string in derived class of DbConext(In your case it is MyEntities) then DbContext will automatically search for a connection string in root web.config file whoes name is same as derived class name (In your case it is My Entities).
I had this problem when running MSTest. I could not get it to work without the "noisolation" flag.
Hopefully this helps someone. Cost me a lot of time to figure that out. Everything ran fine from the IDE. Something weird about the Entity Framework in this context.
Regular migrations
There are two options - the first one that everyone here has suggested is to ensure that the connection string is in the Web.config file of the project. When working with connection strings from Azure application settings, that means overwriting your Web.config values with the Azure values.
Azure or automatic migrations (programmatic)
There's a second option available if you're running migrations programmatically, that allows you to run migrations using a connection string that's obtained dynamically (or via Azure application settings) without storing it in Web.config:
When setting the configuration's TargetDatabase, use the DbConnectionInfo constructor that takes a connection string and a provider name instead of the constructor that takes just a connection name. If your connection string doesn't have a provider name and you're using SQL Server / Azure SQL then use "System.Data.SqlClient"
This could also result in not enough dll references being referenced in the calling code. A small clumsy hack could save your day.
I was following the DB First approach and had created the EDMX file in the DAL Class library project, and this was having reference to the BAL Class library, which in turn was referenced by a WCF service.
Since I was getting this error in the BAL, I had tried the above mentioned method to copy the config details from the App.config of the DAL project, but didn't solve. Ultimately with the tip of a friend I just added a dummy EDMX file to the WCF project (with relevant DB Connectivity etc), so it imported everything necessary, and then I just deleted the EDMX file, and it just got rid of the issue with a clean build.
There is a comment on the top answer by #RyanMann that suggests:
Store your connection strings in one config file, then reference them in other projects by <connectionString configSource="../ProjectDir/SharedConnections.config" />
This is a fantastic suggestion!
It also works to share connection strings between App.config and Web.config files!
Anyone wanting to follow this suggestion, should head on over to this SO answer.
It has a really great step-by-step guide on sharing connection strings among multiple projects in a solution.
The only caveat is that configSource must exist in the same directory or a sub-directory. The link above explains how to use "Add as Link" to get around this.
I had this error when attempting to use EF within an AutoCAD plugin. CAD plugins get the connection string from the acad.exe.config file. Add the connect string as mentioned above to the acad config file and it works.
Credit goes to Norman.Yuan from ADN.Network.
If you are using an MVVM model, try to copy the connection strings to all parts of your project.
For example, if your solution contains two projects, the class library project and the wpf project, you must copy the connection strings of the backend project (library class porject) and place a copy in the App.config file of the wpf project.
<connectionStrings>
<add name="DBEntities" ... />
</connectionStrings>
Hope it's helpful for you :)
Add Connectoinstrnig in web.config file
<ConnectionStiring> <add name="dbName" Connectionstring=" include provider name too" ></ConnectionStiring>

Edmx .net 4.0 The specified named connection is either not found

The specified named connection is either not found in the configuration, not intended to be used with the EntityClient Provider, not valid."
I have a working console project. However when I tried to copy the exe and the app.config (same folder) to a live server it didn't work and got the following error. Could it be a domain issue, or some setting that's baked in? I'm pretty sure it has access to databases since I have used other projects except this time is different because I chose edmx.
<connectionStrings>
<add name="AdvWorksEntities" connectionString="metadata=res://*/GroupsModel.csdl|res: //*/GroupsModel.ssdl|res://*/GroupsModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=abcd;Initial Catalog=AdvWorks;Persist Security Info=True;User ID=user;Password=pass;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
Solution
The app.config is a file name used in a project. However, when it is compiled, the file name becomes application's exe name + .config.
For example, if the application name is "sample.exe", then the configuration name should be "sample.exe.config".

Categories

Resources