The underlying provider failed on open ошибка

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

asked Mar 19, 2010 at 4:36

senzacionale's user avatar

senzacionalesenzacionale

20.5k67 gold badges204 silver badges316 bronze badges

7

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's user avatar

answered Jun 21, 2010 at 2:17

Christian Payne's user avatar

Christian PayneChristian Payne

7,0815 gold badges39 silver badges59 bronze badges

8

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's user avatar

Domysee

12.7k10 gold badges53 silver badges85 bronze badges

answered Oct 26, 2010 at 10:28

kerem's user avatar

keremkerem

2,6991 gold badge32 silver badges37 bronze badges

2

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.

answered May 5, 2015 at 17:52

Majid's user avatar

MajidMajid

13.9k15 gold badges77 silver badges113 bronze badges

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.

answered Jul 21, 2011 at 10:19

dooburt's user avatar

dooburtdooburt

3,01010 gold badges41 silver badges59 bronze badges

3

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's user avatar

answered Sep 26, 2013 at 11:52

Jaisankar's user avatar

JaisankarJaisankar

4531 gold badge5 silver badges10 bronze badges

1

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.

answered Jan 3, 2013 at 16:03

atconway's user avatar

atconwayatconway

20.7k31 gold badges159 silver badges229 bronze badges

7

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.

answered Feb 1, 2013 at 20:05

user2033790's user avatar

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

answered Nov 5, 2012 at 15:46

79E09796's user avatar

79E0979679E09796

2,1401 gold badge20 silver badges33 bronze badges

1

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's user avatar

answered Jan 30, 2014 at 20:28

Rajesh's user avatar

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's user avatar

Matt Fenwick

48.2k22 gold badges128 silver badges192 bronze badges

answered Feb 27, 2012 at 19:52

James Wilkins's user avatar

James WilkinsJames Wilkins

6,8763 gold badges49 silver badges73 bronze badges

1

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

persist security info=True

answered Apr 17, 2013 at 13:47

FV01's user avatar

FV01FV01

113 bronze badges

0

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's user avatar

Beryllium

12.8k10 gold badges56 silver badges86 bronze badges

answered Sep 30, 2013 at 15:35

sparhea's user avatar

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.

answered Nov 4, 2013 at 16:49

alexk's user avatar

alexkalexk

1,2641 gold badge11 silver badges16 bronze badges

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

Peter Mortensen's user avatar

answered Aug 28, 2012 at 22:09

Ravi Thiagarajan's user avatar

0

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's user avatar

answered May 9, 2013 at 10:28

Gökhan Yılmaz's user avatar

Gökhan YılmazGökhan Yılmaz

751 gold badge1 silver badge6 bronze badges

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

answered Feb 28, 2017 at 0:42

Tom Stickel's user avatar

Tom StickelTom Stickel

19.6k6 gold badges111 silver badges113 bronze badges

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's user avatar

S1r-Lanzelot

2,2063 gold badges31 silver badges46 bronze badges

answered Apr 16, 2018 at 11:04

m4rt1n's user avatar

m4rt1nm4rt1n

431 silver badge7 bronze badges

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!

answered May 18, 2013 at 18:54

rikket's user avatar

rikketrikket

2,3677 gold badges46 silver badges74 bronze badges

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…

answered Jul 25, 2014 at 9:14

iber's user avatar

iberiber

511 silver badge4 bronze badges

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's user avatar

answered Aug 4, 2013 at 13:52

user2650536's user avatar

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's user avatar

answered Dec 9, 2013 at 17:23

Erez Robinson's user avatar

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's user avatar

answered May 2, 2014 at 14:01

Connell's user avatar

ConnellConnell

13.9k11 gold badges59 silver badges92 bronze badges

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

answered Jan 17, 2015 at 19:25

Gabriel's user avatar

GabrielGabriel

2,01114 silver badges14 bronze badges

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.

answered Sep 16, 2015 at 15:07

Jaydeep Shil's user avatar

Jaydeep ShilJaydeep Shil

1,91422 silver badges21 bronze badges

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);
    }

answered Nov 4, 2015 at 13:23

dEVmARCO's user avatar

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.

answered Aug 11, 2016 at 20:02

live-love's user avatar

live-lovelive-love

49.1k22 gold badges240 silver badges204 bronze badges

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

answered Jul 25, 2017 at 4:59

Abdur Rahim's user avatar

Abdur RahimAbdur Rahim

3,97514 gold badges44 silver badges83 bronze badges

1

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

answered Jun 6, 2022 at 2:51

Horev Ivan's user avatar

Horev IvanHorev Ivan

2693 silver badges9 bronze badges

Я использовал .mdf для подключения к database и entityClient. Теперь я хочу изменить строку подключения так, чтобы не было файла .mdf.

Правильно ли соответствует connectionString?

<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" />

Потому что я всегда получаю ошибку:

Недопустимый базовый поставщик при открытии

4b9b3361

Ответ 1

У меня была эта ошибка и я нашел несколько решений:

Глядя на вашу строку подключения, она выглядит действительной. Я нашел этот пост в блоге, проблема в том, что они использовали Integrated Security. Если вы работаете в IIS, вашему пользователю IIS необходим доступ к базе данных.

Если вы используете Entity Framework с транзакциями, автоматически открывается Entity Framework и закрывает соединение с каждым вызовом базы данных. Поэтому при использовании транзакций вы пытаетесь распространить транзакцию на несколько соединений. Это поднимается до MSDTC.

(См. эту ссылку для получения дополнительной информации.)

Изменение моего кода на следующее исправлено:

using (DatabaseEntities context = new DatabaseEntities())
{
    context.Connection.Open();
    // the rest
}

Ответ 2

context.Connection.Open() не помог решить мою проблему, поэтому я попытался включить «Разрешить удаленные клиенты» в конфигурации DTC, не более ошибок.

В Windows 7 вы можете открыть конфигурацию DTC, запустив dcomcnfg, Службы компонентов → Компьютеры → Мой компьютер → Координатор распределенных транзакций → Щелкните правой кнопкой мыши на Local DTC → Безопасность.

Ответ 3

Я обнаружил, что проблема в том, что у меня был путь к серверу в строке подключения в одном из этих вариантов:

SERVER\SQLEXPRESS
SERVER

Когда я действительно должен был:

.\SQLEXPRESS

По какой-то причине я получил ошибку, когда ему было трудно найти экземпляр SQL.

Ответ 4

Вы должны увидеть innerException, чтобы увидеть, какая внутренняя причина метания
ошибка есть.

В моем случае исходная ошибка:

Невозможно открыть физический файл «D:\Projects2\xCU\xCU\App_Data\xCUData_log.ldf». Ошибка операционной системы 5: «5 (Доступ запрещен.)». Не удалось выполнить попытку присоединения базы данных с автоименованием для файла D:\Projects2\xCU\xCU\App_Data\xCUData.mdf. База данных с тем же именем существует или указанный файл не может быть открыт или находится на общем ресурсе UNC.

который разрешен путем предоставления полного разрешения текущему пользователю для доступа к связанным файлам mdf и ldf с использованием свойств файлов.

Ответ 5

Это обычная проблема. Даже я столкнулся с этой проблемой. На машине разработки, настроенной с проверкой подлинности Windows, она отлично работает:

<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" />

После размещения в IIS с той же конфигурацией я получил эту ошибку:

Недопустимый базовый поставщик при открытии

Было решено изменить connectionString в файле конфигурации:

<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" />

Другие распространенные ошибки могут быть:

  • Служба базы данных может быть остановлена ​​
  • Атрибуты источника данных, указывающие на локальную базу данных с проверкой подлинности Windows и размещенные в IIS
  • Имя пользователя и пароль могут быть неправильными.

Ответ 6

Когда вы получаете это исключение, обязательно разворачивайте детали и просматривайте внутренние детали исключений, так как они будут содержать подробную информацию о том, почему логин завершился неудачно. В моем случае строка подключения содержала пользователя, который не имел доступа к моей базе данных.

Независимо от того, используете ли вы интегрированную безопасность (контекст зарегистрированного пользователя Windows) или отдельную учетную запись SQL, убедитесь, что у пользователя есть соответствующий доступ в разделе «Безопасность» для базы данных, к которой вы пытаетесь получить доступ, чтобы предотвратить эту проблему.

Ответ 7

У меня была аналогичная проблема с SQL Server Express Edition на Windows Server 2003. Я просто добавил службу сети в качестве пользователя в безопасности базы данных.

Ответ 8

Это также может произойти, если вы восстановите базу данных, а пользователь уже существует с другой схемой, в результате чего вам не удастся назначить правильные разрешения.

Чтобы исправить этот прогон:

USE your_database
EXEC sp_change_users_login 'Auto_Fix', 'user', NULL, 'cf'
GO
EXEC sp_change_users_login 'update_one', 'user', 'user'
GO

Ответ 9

Служба SQL Server Express не была настроена автоматически.

1) Перейдите на панель управления
2) Администрирование
3) Обслуживание
4) Установите SQL Server express для запуска автоматически, щелкнув по нему
5) Щелкните правой кнопкой мыши и запустите службу

Я надеюсь, что это поможет.

Ответ 10

Убедитесь, что значение каждого элемента в строке подключения правильно. В моем случае я получал ту же ошибку, потому что имя каталога (имя базы данных), указанное в строке подключения, было неправильным.

Ответ 11

У меня была аналогичная проблема с исключениями из-за состояния подключения, тогда я понял, что у меня есть переменная класса домена, помеченная как статическая (по ошибке).

Я предполагаю, что после того, как библиотека сервисов будет загружена в память, каждый новый вызов заканчивается тем же значением статической переменной (экземпляр службы домена), что вызывает конфликты через состояние соединения.

Я также думаю, что каждый вызов клиента привел к появлению нового потока, поэтому несколько потоков, обращающихся к одному и тому же экземпляру службы домена, приравнивались к крушению поезда.

Ответ 12

Я избавился от этого, сбросив IIS, но все еще используя Integrated Authentication в строке подключения.

Ответ 13

Я опубликовал аналогичную проблему здесь, работая с SQL 2012 db, размещенным на Amazon RDS. Проблема была в строке соединения — у меня было «Имя приложения» и «Приложение» . Как только я удалил их, он сработал.

Entity Framework 5 и Amazon RDS -» Исходный провайдер отказался от Open. «

Ответ 14

Определение нового правила Брандмауэр Windows для SQL Server (и для порта 1433) на серверной машине разрешает эту ошибку (если ваше имя сервера, имя пользователя или пароль не ошибочны в вашей строке подключения…).

Ответ 15

У меня была аналогичная ошибка с внутренним исключением, как показано ниже:

операция недействительна для состояния транзакции

Я мог бы решить эту проблему, включив параметры безопасности DTC.

Перейдите в «Свойства кода DTC», в разделе «Вкладка» Безопасность «, проверьте ниже

  • Доступ к сети DTC
  • Разрешить удаленные клиенты
  • Связь с диспетчером транзакций
  • Разрешить входящие
  • Разрешить исходящие

Ответ 16

Если вам удастся получить эту ошибку в веб-приложении ASP.NET, в дополнение к другим упомянутым вопросам проверьте следующее:

  • Разрешения безопасности пользователя базы данных (пользователям разрешен доступ к вашей базе данных.
  • Проверьте пул приложений в IIS и убедитесь, что он правильный, которому разрешен доступ к вашей базе данных.

Ответ 17

У меня возникла эта проблема, потому что был добавлен вход для пула приложений, в котором было запущено это приложение.

В IIS:

  • Найдите пул приложений, нажав на свой сайт и перейдя в «Основные настройки».

  • Перейдите в пулы приложений.

  • Нажмите на пул приложений вашего сайта.

  • Нажмите «Дополнительные настройки».

  • В Identity введите учетную запись и пароль.

  • Перезагрузите свой сайт и повторите попытку.

Ответ 18

У меня была такая же проблема, но то, что сработало для меня, было удаление этого из строки подключения:

persist security info=True

Ответ 19

Общей ошибкой, которую я делал, потому что я перемещал приложение с одного компьютера на другой, и ни одно из вышеперечисленных действий не было, я забыл скопировать строку подключения как в App.Config, так и в Web.Config!

Ответ 20

Я тоже столкнулся с той же проблемой. Теперь я сделал это, удалив имя пользователя и пароль из строки подключения.

Ответ 21

Для меня это была просто ошибка:

Я использовал Amazon EC2, и я использовал свой эластичный IP-адрес в строке подключения, но когда я изменил IP-адреса, я забыл обновить свои строка подключения.

Ответ 22

У меня внезапно возникла эта ошибка внезапно на одном из наших сайтов. В моем случае оказалось, что пароль пользователя SQL истек! Отключить окно срока действия пароля в SQL Server Management Studio сделал трюк!

Ответ 23

У меня была аналогичная проблема: в моих тестах я всегда получал эту ошибку. Я узнал, что моя «Служба распределенных транзакций» не была запущена (запустите: services.msc → start «Distributed Transaction Service» (лучше всего настроить ее на автоматический запуск)). После того, как я это сделал, он работал как шарм…

Ответ 24

Я скопировал файлы базы данных (.mdf/.ldf) в папку App_Data, чтобы избавиться от этого исключения.

Ответ 25

У меня была такая же проблема несколько дней назад, используя «Integrated Security = True»; в строке соединения вам нужно запустить идентификатор пула приложений в разделе «localsystem». Конечно, это не рекомендуется, но для тестирования он выполняет задание.

Вот как вы можете изменить идентификатор в IIS 7:
http://www.iis.net/learn/manage/configuring-security/application-pool-identities

Ответ 26

В IIS установите Идентификатор учетной записи пула приложений как учетная запись службы или учетная запись администратора или учетная запись ant, у которой есть разрешение на выполнение операции над этой базой данных.

Ответ 27

В моем случае у меня было несоответствие между именем строки подключения, которое я регистрировал в конструкторе контекста, вместо имени в моем web.config. Простая ошибка, вызванная копированием и вставкой: D

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

Ответ 28

У меня такая же ошибка, я обнаружил, что при изменении myStringString
к новому источнику данных
я забыл изменить имя пользователя и passowrd для новой базы данных

Ответ 29

Я также имел эту ошибку, если имя экземпляра SQL Server не указано, а на узле SQL установлено несколько экземпляров SQL. Вот несколько примеров, поясняющих:

Строка подключения ниже приводит к исключению «Недействительный базовый поставщик при открытии» без внутреннего исключения в приложении .NET WebForms:

 connectionString="metadata=res://*/Entities.csdl|res://*/Entities.ssdl|res://*/Entities.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=localhost;Initial Catalog=Entities;User ID=user;Password=password;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient"

Следующая строка подключения выполняется, как и ожидалось, в приложении .net WebForms, где среда SQL имеет несколько экземпляров. Редкий я знаю, но у меня есть несколько разных экземпляров SQL в моей dev-блоке для размещения разных проектов:

 connectionString="metadata=res://*/Entities.csdl|res://*/Entities.ssdl|res://*/Entities.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=localhost\SQLSERVER2014;Initial Catalog=Entities;User ID=user;Password=password;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient"

Ответ 30

в моем случае адрес сервера был изменен администратором сервера, поэтому мне пришлось изменить строку подключения на новый адрес сервера


First published on MSDN on Aug 09, 2012

My name is Archana CM from Microsoft SQL Developer Support team, we support many data access technologies including Entity Framework, SSIS.

I had chance to work with developer who was having issues in his Entity Framework, one of the issue was while adding data to .mdf file which was on file system.

In today’s blog I am sharing my experience on how we could resolve the issue for him and what issues he was facing.

It was Windows application and Entity Framework was used. As a backend SQLExpress was used in his application and he was saving data to .mdf file which was on file system.

When we executed the application and while trying to add data to .mdf file we could see below error message

Message: The underlying provider failed on Open.

Stack trace : at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)

at System.Data.EntityClient.EntityConnection.Open()

at System.Data.Objects.ObjectContext.EnsureConnection()

at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)

at System.Data.Objects.ObjectContext.SaveChanges()

at EFLenoard.DataMgr.AddFacility(String name, String address, String city) in D:\Research\EFParentChildInsert\EFParentChildInsert2010\DataMgr.cs:line 35

Inner Exception : InnerException = {«An attempt to attach an auto-named database for file D:\\Research\\EFParentChildInsert\\EFParentChildInsert2010\\bin\\Debug\\SplDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC shared …

Here is the connection string that was used, while issue was occurring.

<connectionStrings>

<add name=»SQLDBEntities» connectionString=»metadata=res://*/SplDBModel.csdl|res://*/SplDBModel.ssdl|res://*/SplDBModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\SQLDB.mdf;integrated security=True;user instance=True;multipleactiveresultsets=True;App=EntityFramework&quot;» providerName=»System.Data.EntityClient» />

</connectionStrings>

In this case, Windows authentication with user instance was used to connect to SQL server which was mainly causing the issue.

In order to resolve the above issue, we had 2 solutions


Solution 1:

In the existing connection string to remove the

“user Instance=true”

and it works.

Probable cause of the issue could be as below:


  • The user instance cannot attach the database because the user does not have the required permissions. The user instance executes in the context of the user who opened the connection—not the normal SQL Server service account. The user who opened the user instance connection must have write permissions on the .mdf and .ldf files that are specified in the AttachDbFilename option of the connection string.



  • Another common issue is when you open a database file successfully when the database is attached to the SQL Server Express instance, but fails when you try to open it from the Visual Studio IDE. This might occur because the SQL Server Express instance is running as «NT AUTHORITY\NETWORK SERVICE,» while the IDE is running as windows account. Therefore, the permissions may not work.



  • A variation of this issue is when the user that opens the user instance connection has read permissions on the database files but does not have write permissions. If you get a message saying that the database is opened as read only, you need to change the permissions on the database file.

  • The other main issue with user instances occurs because SQL Server opens database files with exclusive access. This is necessary because SQL Server manages the locking of the database data in its memory. Thus, if more than one SQL Server instance has the same file open, there is the potential for data corruption. If two different user instances use the same database file, one instance must close the file before the other instance can open it. There are two common ways to close database files, as follows.


    • User instance databases have the


      Auto Close


      option set so that if there are no connections to a database for 8-10 minutes, the database shuts down and the file is closed. This happens automatically, but it can take a while, especially if connection pooling is enabled for your connections.

    • Detaching the database from the instance by calling


      sp_detach_db


      will close the file. This is the method Visual Studio uses to ensure that the database file is closed when the IDE switches between user instances. For example, you are using the IDE to design a data-enabled Web page. You press F5 to run the application. The IDE detaches the database so that ASP.NET can open the database files. If you leave the database attached to the IDE and try to run the ASP page from your browser, ASP.NET cannot open the database because the file is still in use by the IDE.


Solution 2:

We created new connection to database with SQL Authentication as a workaround.

Thus connection string turns out to be as below.

<connectionStrings>

<add name=»SQLDBEntities» connectionString=»metadata=res://*/SplDBModel.csdl|res://*/SplDBModel.ssdl|res://*/SplDBModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQLEXPRESS;attachdbfilename=D:\SQLDB.mdf;persist security info=True;

user id=saa;password=***;multipleactiveresultsets=True;App=EntityFramework&quot;» providerName=»System.Data.EntityClient» />

</connectionStrings>

Once applying either of these solutions, with below code we could save data to .mdf file which was on file system. By attached the .mdf file to SQL Server data can be confirmed.


public class DatatoMDFOnFileSystem


{


private SQLDBEntities _sqlDataContext = new SQLDBEntities();


private string _errorMessage;


public long AddDatatoMDFOnFileSystem(string name, string address, string city)


{


_errorMessage = String.Empty;


try


{


string connectString = ConfigurationManager.ConnectionStrings[«SQLDBEntities»].ToString();


using (_sqlDataContext = new SQLDBEntities(connectString))


{


EFDatatoMDFOnFileSystem efDatatoMDFOnFileSystem = EFDatatoMDFOnFileSystem.CreateEFDatatoMDFOnFileSystem(0, name, address, city);


if (efDatatoMDFOnFileSystem != null)


{


_sqlDataContext.AddToEFDatatoMDFOnFileSystem(efDatatoMDFOnFileSystem);


_sqlDataContext.SaveChanges();


id = efDatatoMDFOnFileSystem.Id;


Console.WriteLine(String.Format(«Record added with id, {0}.», id));


}


}


}


catch (Exception err)


{


_errorMessage = err.Message;


}


finally


{


Console.WriteLine(«Error Message, {0}.», _errorMessage);


}


return id;


}


}

Happy Coding!!!!


Author : Archana , SQL Developer Engineer , Microsoft


Reviewed by : Snehadeep(MSFT), SQL Developer Technical Lead, Microsoft

Scenario:

A Windows application with Entity Framework and SQL Express backend was trying to save data to .mdf file on the file system.

When the application is executed by adding data to the .mdf file, the below error occurs: 

Message: The underlying provider failed on Open.

Stack trace : at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)

at System.Data.EntityClient.EntityConnection.Open()

at System.Data.Objects.ObjectContext.EnsureConnection()

at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)

at System.Data.Objects.ObjectContext.SaveChanges()

at EFLenoard.DataMgr.AddFacility(String name, String address, String city) in D:\Research\EFParentChildInsert\EFParentChildInsert2010\DataMgr.cs:line 35

Inner Exception : InnerException = {«An attempt to attach an auto-named database for file D:\\Research\\EFParentChildInsert\\EFParentChildInsert2010\\bin\\Debug\\SplDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC shared …

The connection string used is indicated below:

<connectionStrings>
<add name="SQLDBEntities" connectionString="metadata=res://*/SplDBModel.csdl|res://*/SplDBModel.ssdl|res://*/SplDBModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\SQLDB.mdf;integrated security=True;user instance=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>

Reason:

Windows Authentication with user instance is used to connect to SQL server is the main cause of the issue.

Fix 1:

Try enabling «Allow Remote Clients» in DTC config. 

In windows 7 the DTC config can be opened by running dcomcnfg. Under Component Services -> Computers -> My Computer -> Distributed Transaction Coordinator -> Right click to Local DTC -> Properties -> Security -> select the option Network DTC Access -> select the option Allow Remote clients as shown below:

Fix 2:

Database service is in Stopped state, go to services list and start it.

Fix 3:

Data Source attributes with SQL authentication may have invalid credentials. Check and enter the correct username and password could be wrong.

Fix 4:

In either case of Windows or SQL Authentication ensure that the user has proper access under ‘Security’ for the database.

Fix 5:

Simply add the network service as a user in the database security.

Fix 6:

Enabling DTC security settings.

Go to Properties of DTC as mentioned in Fix1. Under Security Tab, select the below options:

  • Network DTC Access
  • Transaction Manager Communication
  • Allow Inbound
  • Allow Outbound

Fix 7:

Reset IIS, even in case of using Integrated Security in the connection string.

Fix 8:

Remove the following from the Connection String:

persist security info=True

Fix 9:

With «Integrated Security=True;» in the connection string run the application pool identity under «localsystem».  This surely is not recommended but for testing purposes give it a try.

Follow the below link to change the identity in IIS:

http://www.iis.net/learn/manage/configuring-security/application-pool-identities

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.

Check the connection string in web.config where Data Source=localhost is present. This could be the cause for the error, change it as “DOMAIN_Name\MACHINE_Name”.

Fix 10:

The connection string has a value “user Instance=true”. Removing it clears the error. 

  • The user instance executes in the SQL context and won’t have permissions on the .mdf and .ldf files.
  • Also the user instance to databases have an Auto Close option set. If there are no connections to a database for about 8-10 minutes, this Auto Close automatically shuts downs the database.

Hence it is advisable to remove “user Instance=true” settings from connection string.

Fix 11:

  • Open the command prompt with “Run as administrator” and type the command as netsh Winsock reset
  • Restart your system and try again.

Fix 12:

Step 1: Open Internet Information Service Manager.

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

Step 3: Select the version Pool for your ASP .Net version. Or else select DefaultAppPool which is common for all versions.

Step 4: Right click AppPool selected in previous step and select advanced settings.

Step 5 :In the properties window select Identity and click the button to change the value.

Step 6: Set Local System for built-in accounts and click ok. 



As a data scientist or software engineer you may encounter the The underlying provider failed on Open error when working with Entity Framework 5 and Amazon RDS This error can be frustrating and can cause delays in your project In this article we will explain what this error means and provide a stepbystep guide on how to fix it

As a data scientist or software engineer, you may encounter the “The underlying provider failed on Open” error when working with Entity Framework 5 and Amazon RDS. This error can be frustrating and can cause delays in your project. In this article, we will explain what this error means and provide a step-by-step guide on how to fix it.

What is Entity Framework 5?

Entity Framework 5 is an Object Relational Mapping (ORM) framework developed by Microsoft. It allows developers to interact with a database using object-oriented code rather than writing SQL queries. This makes it easier to work with databases and reduces the amount of code needed to interact with them.

What is Amazon RDS?

Amazon RDS is a relational database service provided by Amazon Web Services (AWS). It allows users to create, operate, and scale relational databases in the cloud. Amazon RDS supports several database engines, including MySQL, PostgreSQL, SQL Server, and Oracle.

The “The underlying provider failed on Open” Error

When working with Entity Framework 5 and Amazon RDS, you may encounter the “The underlying provider failed on Open” error. This error occurs when Entity Framework is unable to establish a connection to the database.

There are several reasons why this error may occur, including:

  • Incorrect connection string
  • Network issues
  • Incorrect database credentials
  • AWS security group settings

How to Fix the Error

To fix the “The underlying provider failed on Open” error, follow these steps:

Step 1: Check the Connection String

The first step is to check the connection string. Make sure that the connection string is correct and that it points to the correct database.

Step 2: Check Network Issues

If the connection string is correct, the next step is to check for network issues. Make sure that your computer can connect to the internet and that there are no firewall issues.

Step 3: Check Database Credentials

If there are no network issues, the next step is to check the database credentials. Make sure that the username and password are correct and that the user has the necessary permissions to access the database.

Step 4: Check AWS Security Group Settings

If the database credentials are correct, the next step is to check the AWS security group settings. Make sure that the security group allows incoming traffic from the IP address of your computer.

Step 5: Update Entity Framework to the Latest Version

If none of the above steps work, the final step is to update Entity Framework to the latest version. Entity Framework 5 is an older version, and newer versions may have fixed the issue you are experiencing.

To update Entity Framework, follow these steps:

  1. Open the NuGet Package Manager Console.
  2. Type the following command: Install-Package EntityFramework
  3. Press Enter.

After updating Entity Framework, try connecting to the database again. The error should be resolved.

Conclusion

The “The underlying provider failed on Open” error can be frustrating, but it is often caused by simple issues such as incorrect connection strings or network issues. By following the steps outlined in this article, you should be able to resolve the error and continue working with Entity Framework 5 and Amazon RDS.

Remember to always check your connection strings, network settings, and database credentials before resorting to updating Entity Framework. Updating to the latest version should always be a last resort.


About Saturn Cloud

Saturn Cloud is your all-in-one solution for data science & ML development, deployment, and data pipelines in the cloud. Spin up a notebook with 4TB of RAM, add a GPU, connect to a distributed cluster of workers, and more. Join today and get 150 hours of free compute per month.

Понравилась статья? Поделить с друзьями:
  • The ui language registration list is invalid ошибка
  • Test drive unlimited 2 ошибка код 2
  • The target principal name is incorrect ошибка
  • The sims 3 ошибка инициализации 0x0175d824
  • The system cannot find the path specified ошибка