245

I was using an .mdf for connecting to a database and entityClient. Now I want to change the connection string so that there will be no .mdf file.

Is the following connectionString correct?

<connectionStrings>
   <!--<add name="conString" connectionString="metadata=res://*/conString.csdl|res://*/conString.ssdl|res://*/conString.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\SQL2008;AttachDbFilename=|DataDirectory|\NData.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />-->
   <add name="conString" connectionString="metadata=res://*/conString.csdl|res://*/conString.ssdl|res://*/conString.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\SQL2008;Initial Catalog=NData;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

Because I always get the error:

The underlying provider failed on Open

senzacionale
  • 20,448
  • 67
  • 204
  • 316
  • 2
    I have same issue here when I try to run under IIS. If I run in VS Server I get no error. – Zote May 06 '10 at 17:32
  • 14
    I had the same issue and removed `Integrated Security` from the connectionstring, created a user and made sure they have `sysadmin` permissions and added that user to the connectionstring. – gotnull Mar 13 '12 at 05:10
  • where is your DB located , if it's on a application hosted on IIS you should place your DB in your App_Data folder and edit the connection string generated by the Entityframework model to look for it there . http://stackoverflow.com/questions/9809442/entity-exception-the-underlying-provider-failed-to-open – eran otzap Mar 22 '12 at 11:57
  • I had this problem, and it was solved by inserting the password in the connection string. – satyrFrost Aug 14 '12 at 04:12
  • Simply removing Integrated Security worked for me when running under IIS – Jon Feb 16 '14 at 23:41
  • See also: http://stackoverflow.com/a/5416812/213550 - may be you didn't create the database, like me :( – VMAtm Apr 01 '16 at 11:38
  • adding port in firewall solves my issue. Here's my reference: https://consignor.zendesk.com/hc/en-us/articles/115000647774-Opening-Windows-Firewall-for-client-connections-to-server – Jed Monsanto Apr 22 '20 at 04:55

31 Answers31

231

I had this error and found a few solutions:

Looking at your connection string, it looks valid. I found this blog post, the problem here is that they were using Integrated Security. If you are running on IIS, your IIS user needs access to the database.

If you are using Entity Framework with Transactions, Entity Framework automatically opens and closes a connection with each database call. So when using transactions, you are attempting to spread a transaction out over multiple connections. This elevates to MSDTC.

(See this reference for more information.)

Changing my code to the following fixed it:

using (DatabaseEntities context = new DatabaseEntities())
{
    context.Connection.Open();
    // the rest
}
Community
  • 1
  • 1
Christian Payne
  • 7,081
  • 5
  • 38
  • 59
  • 7
    How is this done when using Linq to access the tables (using EF4)? – Brett Rigby Jul 30 '10 at 15:15
  • 2
    @Brett Rigby: http://stackoverflow.com/questions/794707/why-doesnt-transactionscope-work-with-entity-framework/794785#794785 covers how to do this with Linq/EF. – Scott Stafford Apr 26 '11 at 15:48
  • 68
    If you are using EF / DBContext, then the correct call is context.Database.Connection.Open(); – live-love Jan 03 '12 at 19:05
  • 3
    I wish I'd read your post instead of skimming it for code when I first found it. My issue (as pointed out in this answer) was that the AppPool user for the CRM 2011 Plugin context had no write access to the Database I'd set up. When I added the user to SQL, the Plugin worked like a charm. – Mike_Matthews_II Mar 08 '13 at 18:31
  • 2
    I didn't have a connection string in my config named after the context I was creating.......check for that also. – Bill Blankenship Jul 03 '13 at 21:31
  • Thanks for the example. I don't know what possessed me to do this, but I had declared a context variable with an internal scope for my class that I used in multiple functions. If one function hadn't disposed of the variable by the time a second function attempted to use it, they would step all over each other. – user942620 Nov 17 '17 at 19:47
  • Check your firewall isn't blocking MSDTC. – Paul Zahra Oct 25 '18 at 13:51
  • Did anyone face the issue in case of a large string being sent from the Entity Framework side to the DB? In my case the string`s size is greate than 1GB. Maybe someone happen to know a way to overcome this? – hellouworld Feb 12 '20 at 16:54
41

context.Connection.Open() didn't help solving my problem so I tried enabling "Allow Remote Clients" in DTC config, no more error.

In windows 7 you can open the DTC config by running dcomcnfg, Component Services -> Computers -> My Computer -> Distributed Transaction Coordinator -> Right click to Local DTC -> Security.

Domysee
  • 12,718
  • 10
  • 53
  • 84
kerem
  • 2,699
  • 1
  • 32
  • 37
  • 11
    In windows 7 you can open the DTC config by running **dcomcnfg**, Component Services -> Computers -> My Computer -> Distributed Transaction Coordinator -> Right click to Local DTC -> Security. – kerem Mar 03 '11 at 16:48
  • 8
    Actually it's Right click to Local DTC -> Properties -> Security – Otto Abnormalverbraucher Jan 19 '17 at 13:47
30

You should see innerException to see what the inner cause of throwing of error is.

In my case, the original error was:

Unable to open the physical file "D:\Projects2\xCU\xCU\App_Data\xCUData_log.ldf". Operating system error 5: "5(Access is denied.)". An attempt to attach an auto-named database for file D:\Projects2\xCU\xCU\App_Data\xCUData.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

which solved by giving full permission to current user for accessing related mdf and ldf files using files' properties.

Majid
  • 13,853
  • 15
  • 77
  • 113
25

I found the problem was that I had the server path within the connection string in one of these variants:

SERVER\SQLEXPRESS
SERVER

When really I should have:

.\SQLEXPRESS

For some reason I got the error whenever it had difficulty locating the instance of SQL.

dooburt
  • 3,010
  • 10
  • 41
  • 59
  • 6
    That might be because you don't have named pipes enabled as a connection method for SQL Server. – Paul Nov 21 '11 at 14:29
  • 1
    @Paul, thanks. It was likely that as it was a new installation of SQL, which rolls out with named pipes disabled. Thanks for the heads-up. +1 – dooburt Dec 05 '11 at 12:48
  • 1
    Thanks for this, I had this issue due to named pipes being disabled. – Patrick Allwood Apr 01 '14 at 08:01
16

This is common issue only. Even I have faced this issue. On the development machine, configured with Windows authentication, it is worked perfectly:

<add name="ShoppingCartAdminEntities" connectionString="metadata=res://*/ShoppingCartAPIModel.csdl|res://*/ShoppingCartAPIModel.ssdl|res://*/ShoppingCartAPIModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQlExpress;initial catalog=ShoppingCartAdmin;Integrated Security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />

Once hosted in IIS with the same configuration, I got this error:

The underlying provider failed on Open

It was solved changing connectionString in the configuration file:

<add name="MyEntities" connectionString="metadata=res://*/ShoppingCartAPIModel.csdl|res://*/ShoppingCartAPIModel.ssdl|res://*/ShoppingCartAPIModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MACHINE_Name\SQlExpress;initial catalog=ShoppingCartAdmin;persist security info=True;user id=sa;password=notmyrealpassword;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />

Other common mistakes could be:

  1. Database service could be stopped
  2. Data Source attributes pointing to a local database with Windows authentication and hosted in IIS
  3. Username and password could be wrong.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jaisankar
  • 453
  • 1
  • 5
  • 10
  • For me the issue was when I created the EF data model it created a connection string that uses the login data from the Data Connections in VS . No user or password was in the connection string so , remove `Integrated Security=True` and replace it with `user id=sa;password=notmyrealpassword` to fix this deployment issue . – LostNomad311 Jun 01 '18 at 21:00
13

When you receive this exception, make sure to expand the detail and look at the inner exception details as it will provide details on why the login failed. In my case the connection string contained a user that did not have access to my database.

Regardless of whether you use Integrated Security (the context of the logged in Windows User) or an individual SQL account, make sure that the user has proper access under 'Security' for the database you are trying to access to prevent this issue.

atconway
  • 20,624
  • 30
  • 159
  • 229
  • I've got the same issue as the original post, verified my hostname, and verified in the inner exception that I'm using the correct user name. SSMS user security looks correct -- the SQL Server account is set up properly and has public access to the database. But, login failed. – Codes with Hammer Feb 18 '14 at 17:06
  • What does the `inner exception` state is the issue? That was my answer here, that it will provide the hidden additional detail needed to understand the true underlying problem. The `inner exception` will not verify that you have the correct logon - it's an exception not a clarification. – atconway Feb 18 '14 at 17:25
  • `Login failed for user 'user'.` – Codes with Hammer Feb 18 '14 at 17:59
  • I also tried adding `NT AUTHORITY\NETWORK SERVICE` to the SQL Server users list. I still got the same rejected login failure. – Codes with Hammer Feb 18 '14 at 18:45
  • SOLVED. I needed to change `data source` to `hostname\SQLEXPRESS`. I had tried `hostname` and `.\SQLEXPRESS` previously. Then I was able to connect with integrated security. Curiously, this is the opposite of **dooburt**'s answer. Curiouser, the SQL Server user name was never able to connect from Visual Studio. – Codes with Hammer Feb 18 '14 at 18:56
  • In my case i set "IntegratedSecurity = true" and the credential is not trusted by the server i'm connecting against. – Harvey Darvey Jul 17 '16 at 10:18
  • This comment saved me hours. Don't overlook it. – GeorgiG Mar 02 '21 at 10:50
5

The SQL Server Express service were not set tostart automatically.

1) Go to control panel 2) Administrative Tools 3) Service 4) Set SQL Server express to start automatically by clicking on it 5) Right click and start the service

I hope that will help.

user2033790
  • 51
  • 1
  • 1
5

I had a similar issue with the SQL Server Express Edition on Windows Server 2003. I simply added the network service as a user in the database security.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Par6
  • 389
  • 1
  • 10
  • 20
3

This can also happen if you restore a database and the user already exists with different schema, leaving you unable to assign the correct permissions.

To correct this run:

USE your_database
EXEC sp_change_users_login 'Auto_Fix', 'user', NULL, 'cf'
GO
EXEC sp_change_users_login 'update_one', 'user', 'user'
GO
79E09796
  • 2,120
  • 1
  • 20
  • 33
  • Absolutely this was the problem. I just restored from a backup. Take a [look](http://www.fileformat.info/tip/microsoft/sql_orphan_user.htm) for detail analyze. – nesimtunc Jul 29 '13 at 05:36
2

I posted a similar issue here, working with a SQL 2012 db hosted on Amazon RDS. The problem was in the connection string - I had "Application Name" and "App" properties in there. Once I removed those, it worked.

Entity Framework 5 and Amazon RDS - "The underlying provider failed on Open."

Community
  • 1
  • 1
wloescher
  • 4,503
  • 2
  • 25
  • 27
2

Make sure that each element value in the connection string being supplied is correct. In my case, I was getting the same error because the name of the catalog (database name) specified in the connection string was incorrect.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rajesh
  • 21
  • 1
1

I got rid of this by resetting IIS, but still using Integrated Authentication in the connection string.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

I had the same problem but what worked for me was removing this from the Connection String:

persist security info=True

FV01
  • 11
  • 3
1

Defining a new Windows Firewall rule for SQL Server (and for port 1433) on the server machine solves this error (if your servername, user login name or password is not wrong in your connection string...).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gökhan Yılmaz
  • 75
  • 1
  • 1
  • 6
1

I had a similar error with the inner exception as below:

operation is not valid for the state of the transaction

I could resolve it by enabling DTC security settings.

Go To Properties of DTC, under Security Tab, check the below

  • Network DTC Access
  • Allow RemoteClients
  • Transaction Manager Communication
  • Allow Inbound
  • Allow Outbound
Beryllium
  • 12,808
  • 10
  • 56
  • 86
sparhea
  • 11
  • 2
1

If you happen to get this error on an ASP.NET web application, in addition to other things mentioned check the following:

  1. Database User Security Permissions (which users are allowed access to your database.
  2. Check your application pool in IIS and make sure it's the correct one that is allowed access to your database.
alexk
  • 1,254
  • 1
  • 11
  • 16
1

NONE of the answers worked for me

I think that some of us all make silly mistakes, there are 100 ways to fail ...

My issue was new project, I setup all the configuration in another project, but the caller was a Web Api project in which I had to copy the same connection string in the Web api project.

I think this is crazy considering I was not even newing up dbcontext or anything from the web api.

Otherwise the class library was trying to look for a Database named

TokenApi.Core.CalContext   

of which my project is named TokenApi.Core and the CalContext is the name of the connection string and the file name

Tom Stickel
  • 19,633
  • 6
  • 111
  • 113
1

I was searching all over the web for this problem. I had the wrong name in the connection string, please check you connection string in web.config. I had name="AppTest" but it should have been name="App".

In my AppTestContext.cs file I had:

public AppTestContext() : this("App") { }

Wrong connection string:

<add connectionString="Data Source=127.0.0.1;Initial Catalog=AppTest;Integrated Security=SSPI;MultipleActiveResultSets=True" name="AppTest" providerName="System.Data.SqlClient" />

Right connection string:

<add connectionString="Data Source=127.0.0.1;Initial Catalog=AppTest;Integrated Security=SSPI;MultipleActiveResultSets=True" name="App" providerName="System.Data.SqlClient" />
S1r-Lanzelot
  • 2,206
  • 3
  • 31
  • 45
m4rt1n
  • 43
  • 1
  • 7
1

I had a similar issue with exceptions due to the connection state, then I realized I had my domain service class variable marked as static (by mistake).

My guess is that once the service library is loaded into memory, each new call ends up using the same static variable value (domain service instance), causing conflicts via the connection state.

I think also that each client call resulted in a new thread, so multiple threads accessing the same domain service instance equated to a train wreck.

Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192
James Wilkins
  • 6,836
  • 3
  • 48
  • 73
  • This is what did it for me too. It seems if you mark it static, it just causes all sorts of problems with the instance it's trying to work with. – Michael J. Gray Jun 27 '12 at 18:39
0

A common mistake that I did because I was moving application from once pc to another and none of the above worked was that I forgot to copy the connection string to both App.Config and Web.Config!

rikket
  • 2,357
  • 7
  • 46
  • 74
0

I was also facing the same issue. Now I have done it by removing the user name and password from the connection string.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

For me it was just a simple mistake:

I used Amazon EC2, and I used my elastic IP address in the connection string, but when I changed IP addresses I forgot to update my connection string.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Erez Robinson
  • 794
  • 4
  • 9
0

I had this error suddenly happen out of the blue on one of our sites. In my case, it turned out that the SQL user's password had expired! Unticking the password expiration box in SQL Server Management Studio did the trick!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Connell
  • 13,925
  • 11
  • 59
  • 92
0

I had a similar problem: In my test-cases executions I always got this error. I found out, that my "Distributed Transaction Service" was not started (run: services.msc -> start "Distributed Transaction Service" (best to set it to start automatic)). After I did that, it worked like a charm...

iber
  • 51
  • 1
  • 4
0

I had the same issue few days ago, using "Integrated Security=True;" in the connection string you need to run the application pool identity under "localsystem" Sure this is not recommended but for testing it does the job.

This is how you can change the identity in IIS 7: http://www.iis.net/learn/manage/configuring-security/application-pool-identities

Gabriel
  • 2,011
  • 14
  • 14
0

In IIS set the App Pool Identity As Service Account user or Administrator Account or ant account which has permission to do the operation on that DataBase.

Jaydeep Shil
  • 1,894
  • 22
  • 21
0

In my case I had a mismatch between the connection string name I was registering in the context's constructor vs the name in my web.config. Simple mistake caused by copy and paste :D

    public DataContext()
        : base(nameOrConnectionString: "ConnStringName")
    {
        Database.SetInitializer<DataContext>(null);
    }

dEVmARCO
  • 31
  • 4
0

I had this problem because the Application Pool login this app was running under had changed.

In IIS:

  • Find the Application pool by clicking on your site and going to Basic Settings.

  • Go to Application Pools.

  • Click on your site's application pool.

  • Click on Advanced Settings.

  • In Identity, enter account login and password.

  • Restart your site and try again.

live-love
  • 48,840
  • 22
  • 240
  • 204
0

I have solved this way.

Step 1: Open Internet Information Service Manager

Step 2: Click on Application Pools in left navigation tree.

Step 3: Select your version Pool. In my case, I am using ASP .Net v4.0. If you dont have this version, select DefaultAppPool.

Step 4: Right click on step 3, and select advanced settings.

Step 5: Select Identity in properties window and click the button to change the value.

Step 6: Select Local System in Built-in accounts combo box and click ok. That's it. Now run your application. Everything works well.

Codeproject Solution : the-underlying-provider-failed-on-open

Abdur Rahim
  • 3,975
  • 14
  • 44
  • 83
  • In other words, the login your application pool is running under, should have a DB access, in case you are using the Integrated Security. – the berserker Apr 03 '18 at 15:22
0

I get this error when call async EF method from sync Main console (await was skipped).

Because async opening a connection was for an already disposed data context.

Solve: call async EF methods correctly

Horev Ivan
  • 270
  • 3
  • 9
-1

You could try to replace the metadata:

metadata=res:///conString.csdl|res:///conString.ssdl|res://*/conString.msl

to:

metadata=res://*/;

LazyTarget
  • 879
  • 1
  • 14
  • 30