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)
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.
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>
I have a very simple web part. I have a single grid view, which I am populating using linq to entities (or at least that's what I want to do). The Entity Data Model .edmx file is located in the same project as the web part, and everything looks to be in working order. When I debug the project, it blows up on the entity model constructor with the error message:
The specified named connection is
either not found in the configuration,
not intended to be used with the
EntityClient provider, or not valid.
My connection string in the App.Config is as follows:
<add name="MyDBEntities" connectionString="metadata=res://*/MyDBEntityModel.csdl|res://*/MyDBEntityModel.ssdl|res://*/MyDBEntityModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=MyServer;Initial Catalog=MyDB;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
The constructor:
public MyDBEntities() : base("name=MyDBEntities", "MyDBEntities")
So, from what I've read elsewhere, my problem is that SharePoint can't see my connection string. Which means, that the App.Config from my project isn't actually getting loaded into SharePoint when I run/debug the project. If that's the case, then how I do set my project up in Visual Studio 2010 to ensure SharePoint picks up the App.Config in addition to the master SharePoint config file. If I have to manually copy the connection string, is there a "best practice" procedure for doing so? Are SharePoint Web Parts combined with the Entity Framework just not ready for prime time?
The SharePoint Tools for Visual Studio 2010 have come along way and will automatically make many of the necessary entries into web.config. Unfortunately, they won't make Entity Framework entries for you. To do this, you'll need to write a feature receiver for your web part project that adds the EF connection string.
The SharePoint API has an object named SPWebConfigModification. You should write a FeatureActivated event that uses this class to make your modification to web.config and then a FeatureDeactivating event that removes the modification.
-Greg
I was wrestling with a the same exception in a SharePoint 2010 WebPart, and I've finally got it working, but here are two important things that I learned along the way.
You must use a farm solution rather than a sandbox solution. The reason for this is, sandbox solutions do not have access to data outside the site collection. A more meaningful exception would have been helpful to solve this quickly, but I was receiving the exception as above.
Your connection string must be in the web.config of the Web Application that you install your WebPart on. It is not added automatically when you install your WebPart, so you must either update the web.config the way Greg lists above, or edit it manually. It sits in C:\inetpub\wwwroot\wss\VirtualDirectories{WebApplicationName}\web.config