Error 50 произошла ошибка local database runtime невозможно создать автоматический экземпляр

I am trying to build an ASP.NET MVC 5 Web Application which has a MyDatabase.mdf file in the App_Data folder. I have SQL Server 2014 Express installed with a LocalDb instance. I can edit the database

To begin — there are 4 issues that could be causing the common LocalDb SqlExpress Sql Server connectivity errors SQL Network Interfaces, error: 50 - Local Database Runtime error occurred, before you begin you need to rename the v11 or v12 to (localdb)mssqllocaldb

Possible Issues
  • You don’t have the services running
  • You don’t have the firelwall ports here
    configured
  • Your install has and issue/corrupt (the steps below help give you a nice clean start)
  • You did not rename the V11 or 12 to mssqllocaldb
 \ rename the conn string from v12.0 to MSSQLLocalDB -like so-> 
 `<connectionStrings>
      <add name="ProductsContext" connectionString="Data Source= (localdb)mssqllocaldb; 
      ...`

I found that the simplest is to do the below — I have attached the pics and steps for help.

First verify which instance you have installed, you can do this by checking the registry& by running cmd

 1. `cmd> Sqllocaldb.exe i` 
 2. `cmd> Sqllocaldb.exe s "whicheverVersionYouWantFromListBefore"` 
if this step fails, you can delete with option `d` cmd> Sqllocaldb.exe d "someDb"
 3. `cmd> Sqllocaldb.exe c "createSomeNewDbIfyouWantDb"` 
 4. `cmd> Sqllocaldb.exe start "createSomeNewDbIfyouWantDb"`

SqlLOCALDb_edited.png


ADVANCED Trouble Shooting Registry configurations

Edit 1, from requests & comments: Here are the Registry path for all versions, in a generic format to track down the registry

Paths

// SQL SERVER RECENT VERSIONS
HKEY_LOCAL_MACHINESOFTWAREMicrosoftMicrosoft SQL Server(instance-name)

// OLD SQL SERVER
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesMSSQLServer
HKEY_LOCAL_MACHINESOFTWAREMicrosoftMSSQLServer
// SQL SERVER 6.0 and above.

HKEY_LOCAL_MACHINESystemCurrentControlSetServicesMSDTC
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesSQLExecutive
// SQL SERVER 7.0 and above

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesSQLServerAgent
HKEY_LOCAL_MACHINESoftwareMicrosoftMicrosoft SQL Server 7
HKEY_LOCAL_MACHINESoftwareMicrosoftMSSQLServ65

Searching

SELECT registry_key, value_name, value_data  
FROM sys.dm_server_registry  
WHERE registry_key LIKE N'%SQLAgent%';

or Run this in SSMS Sql Management Studio, it will give a full list of all installs you have on the server

DECLARE     @SQL VARCHAR(MAX)
SET         @SQL = 'DECLARE @returnValue NVARCHAR(100)'
SELECT @SQL = @SQL + CHAR(13) + 'EXEC   master.dbo.xp_regread

 @rootkey      = N''HKEY_LOCAL_MACHINE'',
 @key          = N''SOFTWAREMicrosoftMicrosoft SQL Server' + RegPath + 'MSSQLServer'',
 @value_name   = N''DefaultData'',
 @value        = @returnValue OUTPUT; 

 UPDATE #tempInstanceNames SET DefaultDataPath = @returnValue WHERE RegPath = ''' + RegPath + '''' + CHAR(13) FROM #tempInstanceNames 

 -- now, with these results, you can search the reg for the values inside reg
 EXEC (@SQL)
 SELECT      InstanceName, RegPath, DefaultDataPath
 FROM        #tempInstanceNames

Trouble Shooting Network configurations

SELECT registry_key, value_name, value_data  
FROM sys.dm_server_registry  
WHERE registry_key LIKE N'%SuperSocketNetLib%';  

  • Remove From My Forums
  • Question

  • Step1: Opened Lightswtich

    Step2: selcted DB and Table Through wizard.

    Step 3: while Build the application getting the following error

    Error 1 An error occurred while establishing a connection to SQL Server instance ‘(LocalDB)v11.0’.
    A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider:
    SQL Network Interfaces, error: 50 — Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
    ) C:Program Files (x86)MSBuildMicrosoftVisualStudioLightSwitchv2.0Microsoft.LightSwitch.targets 146 10 Testproj2

    Could you please recommend, what i have to solve this issue, i am very new to lightswitch.

    Thank you.

    • Edited by

      Monday, April 8, 2013 7:40 AM

Answers

  • Hi,

    LightSwitch used SQL Server 2012 Express LocalDB for tables created by LightSwitch. The error indicated that your SQL Server 2012 Express LocalDB is not working.

    First thing to check is to make sure that you have Microsoft SQL Server 2012 Express LocalDB
    installed on your machine (using Uninstall or change a program window). If not,
    this article is a good introduction to it and how to install it.

    Second thing to check is to make sure the SQL Server (SQLEXPRESS) service is running (using Services window).

    If there are issues with the service itself, either repair the instance or
    this article has good trouble-shooting steps.

    Best regards,
    Huy Nguyen

    • Proposed as answer by
      Angie Xu
      Wednesday, April 24, 2013 7:32 AM
    • Marked as answer by
      Angie Xu
      Tuesday, May 7, 2013 3:15 AM

To begin — there are 4 issues that could be causing the common LocalDb SqlExpress Sql Server connectivity errors SQL Network Interfaces, error: 50 - Local Database Runtime error occurred, before you begin you need to rename the v11 or v12 to (localdb)mssqllocaldb

Possible Issues
  • You don’t have the services running
  • You don’t have the firelwall ports here
    configured
  • Your install has and issue/corrupt (the steps below help give you a nice clean start)
  • You did not rename the V11 or 12 to mssqllocaldb
 \ rename the conn string from v12.0 to MSSQLLocalDB -like so-> 
 `<connectionStrings>
      <add name="ProductsContext" connectionString="Data Source= (localdb)mssqllocaldb; 
      ...`

I found that the simplest is to do the below — I have attached the pics and steps for help.

First verify which instance you have installed, you can do this by checking the registry& by running cmd

 1. `cmd> Sqllocaldb.exe i` 
 2. `cmd> Sqllocaldb.exe s "whicheverVersionYouWantFromListBefore"` 
if this step fails, you can delete with option `d` cmd> Sqllocaldb.exe d "someDb"
 3. `cmd> Sqllocaldb.exe c "createSomeNewDbIfyouWantDb"` 
 4. `cmd> Sqllocaldb.exe start "createSomeNewDbIfyouWantDb"`

SqlLOCALDb_edited.png


ADVANCED Trouble Shooting Registry configurations

Edit 1, from requests & comments: Here are the Registry path for all versions, in a generic format to track down the registry

Paths

// SQL SERVER RECENT VERSIONS
HKEY_LOCAL_MACHINESOFTWAREMicrosoftMicrosoft SQL Server(instance-name)

// OLD SQL SERVER
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesMSSQLServer
HKEY_LOCAL_MACHINESOFTWAREMicrosoftMSSQLServer
// SQL SERVER 6.0 and above.

HKEY_LOCAL_MACHINESystemCurrentControlSetServicesMSDTC
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesSQLExecutive
// SQL SERVER 7.0 and above

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesSQLServerAgent
HKEY_LOCAL_MACHINESoftwareMicrosoftMicrosoft SQL Server 7
HKEY_LOCAL_MACHINESoftwareMicrosoftMSSQLServ65

Searching

SELECT registry_key, value_name, value_data  
FROM sys.dm_server_registry  
WHERE registry_key LIKE N'%SQLAgent%';

or Run this in SSMS Sql Management Studio, it will give a full list of all installs you have on the server

DECLARE     @SQL VARCHAR(MAX)
SET         @SQL = 'DECLARE @returnValue NVARCHAR(100)'
SELECT @SQL = @SQL + CHAR(13) + 'EXEC   master.dbo.xp_regread

 @rootkey      = N''HKEY_LOCAL_MACHINE'',
 @key          = N''SOFTWAREMicrosoftMicrosoft SQL Server' + RegPath + 'MSSQLServer'',
 @value_name   = N''DefaultData'',
 @value        = @returnValue OUTPUT; 

 UPDATE #tempInstanceNames SET DefaultDataPath = @returnValue WHERE RegPath = ''' + RegPath + '''' + CHAR(13) FROM #tempInstanceNames 

 -- now, with these results, you can search the reg for the values inside reg
 EXEC (@SQL)
 SELECT      InstanceName, RegPath, DefaultDataPath
 FROM        #tempInstanceNames

Trouble Shooting Network configurations

SELECT registry_key, value_name, value_data  
FROM sys.dm_server_registry  
WHERE registry_key LIKE N'%SuperSocketNetLib%';  

To begin — there are 4 issues that could be causing the common LocalDb SqlExpress Sql Server connectivity errors SQL Network Interfaces, error: 50 - Local Database Runtime error occurred, before you begin you need to rename the v11 or v12 to (localdb)mssqllocaldb

Possible Issues
  • You don’t have the services running
  • You don’t have the firelwall ports here
    configured
  • Your install has and issue/corrupt (the steps below help give you a nice clean start)
  • You did not rename the V11 or 12 to mssqllocaldb
 \ rename the conn string from v12.0 to MSSQLLocalDB -like so-> 
 `<connectionStrings>
      <add name="ProductsContext" connectionString="Data Source= (localdb)mssqllocaldb; 
      ...`

I found that the simplest is to do the below — I have attached the pics and steps for help.

First verify which instance you have installed, you can do this by checking the registry& by running cmd

 1. `cmd> Sqllocaldb.exe i` 
 2. `cmd> Sqllocaldb.exe s "whicheverVersionYouWantFromListBefore"` 
if this step fails, you can delete with option `d` cmd> Sqllocaldb.exe d "someDb"
 3. `cmd> Sqllocaldb.exe c "createSomeNewDbIfyouWantDb"` 
 4. `cmd> Sqllocaldb.exe start "createSomeNewDbIfyouWantDb"`

SqlLOCALDb_edited.png


ADVANCED Trouble Shooting Registry configurations

Edit 1, from requests & comments: Here are the Registry path for all versions, in a generic format to track down the registry

Paths

// SQL SERVER RECENT VERSIONS
HKEY_LOCAL_MACHINESOFTWAREMicrosoftMicrosoft SQL Server(instance-name)

// OLD SQL SERVER
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesMSSQLServer
HKEY_LOCAL_MACHINESOFTWAREMicrosoftMSSQLServer
// SQL SERVER 6.0 and above.

HKEY_LOCAL_MACHINESystemCurrentControlSetServicesMSDTC
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesSQLExecutive
// SQL SERVER 7.0 and above

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesSQLServerAgent
HKEY_LOCAL_MACHINESoftwareMicrosoftMicrosoft SQL Server 7
HKEY_LOCAL_MACHINESoftwareMicrosoftMSSQLServ65

Searching

SELECT registry_key, value_name, value_data  
FROM sys.dm_server_registry  
WHERE registry_key LIKE N'%SQLAgent%';

or Run this in SSMS Sql Management Studio, it will give a full list of all installs you have on the server

DECLARE     @SQL VARCHAR(MAX)
SET         @SQL = 'DECLARE @returnValue NVARCHAR(100)'
SELECT @SQL = @SQL + CHAR(13) + 'EXEC   master.dbo.xp_regread

 @rootkey      = N''HKEY_LOCAL_MACHINE'',
 @key          = N''SOFTWAREMicrosoftMicrosoft SQL Server' + RegPath + 'MSSQLServer'',
 @value_name   = N''DefaultData'',
 @value        = @returnValue OUTPUT; 

 UPDATE #tempInstanceNames SET DefaultDataPath = @returnValue WHERE RegPath = ''' + RegPath + '''' + CHAR(13) FROM #tempInstanceNames 

 -- now, with these results, you can search the reg for the values inside reg
 EXEC (@SQL)
 SELECT      InstanceName, RegPath, DefaultDataPath
 FROM        #tempInstanceNames

Trouble Shooting Network configurations

SELECT registry_key, value_name, value_data  
FROM sys.dm_server_registry  
WHERE registry_key LIKE N'%SuperSocketNetLib%';  

GENDALF_ISTARI

15 / 32 / 19

Регистрация: 20.08.2013

Сообщений: 740

1

08.02.2016, 01:14. Показов 12462. Ответов 12

Метки нет (Все метки)


Проблема подключения к серверу базы
Локально все работает
выводит данные

Publich->File публикуем проект в отдельную папку
Потом IIS ->Добавить сайт добавляем этот каталог

А как подключать SQL к IIS серверу то возникает проблема
с Сайты->Строка Подключения

Вот строка Web.Config которую подключаю в IIS

XML
1
2
3
4
<connectionStrings>
        <remove name="LocalSqlServer" />
        <add connectionString="Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=|DataDirectory|Database_base.mdf;Integrated Security=True" providerName="System.Data.SqlClient" name="DB_Context" />
  </connectionStrings>

Строка подключения локальная обычная вот Web.Config

XML
1
2
3
4
 <connectionStrings>
    <add name="DB_Context" connectionString="Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename='|DataDirectory|Database_base.mdf';Integrated Security=True"
 providerName="System.Data.SqlClient"/>
  </connectionStrings>

Проект ссылка вот: WebApplication_base_test_manual.rar

К сожалению выводит вот (Как решить проблему товарищи)

Миниатюры

Ошибка Local Database Runtime. Невозможно создать автоматический экземпляр
 

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Администратор

Эксперт .NET

15248 / 12287 / 4904

Регистрация: 17.03.2014

Сообщений: 24,884

Записей в блоге: 1

08.02.2016, 14:24

2

GENDALF_ISTARI, в ошибке сказано что в журнале событий была сделана запись с инфорамацией об ошибке. Найди её и выложи сюда.



1



Эксперт .NET

11074 / 7638 / 1178

Регистрация: 21.01.2016

Сообщений: 28,682

08.02.2016, 17:38

3

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

Добавлено через 3 минуты
Вот вам инструкция по использованию LocalDB с IIS.



1



15 / 32 / 19

Регистрация: 20.08.2013

Сообщений: 740

08.02.2016, 18:07

 [ТС]

4

хорошо Найду шас выложу , честно не понимаю IIS он что должен иметь пароль и логин в строке в Web.Config для персонального входа не пойму где это и как видить



0



15 / 32 / 19

Регистрация: 20.08.2013

Сообщений: 740

08.02.2016, 18:39

 [ТС]

5

Вот нашел журнал называется
Диспетчер IIS-> Начальная страница(test-host.zapto.org)->IIS->Введение Журнала
(путь к логам %SystemDrive%inetpublogsLogFiles)

там папки
W3SVC1
W3SVC2
W3SVC3

я упаковал в архив LogFiles.rar их, и прикрепил к вашему серваку))
объясните как правильно базу подключить к IIS
да я сделаю на HTML инструкцию, и для себя, и вам скину))



0



Администратор

Эксперт .NET

15248 / 12287 / 4904

Регистрация: 17.03.2014

Сообщений: 24,884

Записей в блоге: 1

08.02.2016, 18:58

6

Цитата
Сообщение от GENDALF_ISTARI
Посмотреть сообщение

Вот нашел журнал называется
Диспетчер IIS-> Начальная страница(test-host.zapto.org)->IIS->Введение Журнала
(путь к логам %SystemDrive%inetpublogsLogFiles)

Это не то. Речь идет о журнале событий Windows который просматривается с помощью Event Viewer.



1



15 / 32 / 19

Регистрация: 20.08.2013

Сообщений: 740

08.02.2016, 19:30

 [ТС]

7

Администрирвание->Просмотр событий
по этой статье Windows Event

На фото события
Я их сохранил в файл log_error.evtx прикрепил к вашему серваку, в архиве log_error.rar
можно открыть Просмотр событий -> справа Импортировать кажется

Миниатюры

Ошибка Local Database Runtime. Невозможно создать автоматический экземпляр
 



0



Эксперт .NET

11074 / 7638 / 1178

Регистрация: 21.01.2016

Сообщений: 28,682

08.02.2016, 19:55

8

GENDALF_ISTARI, я же вам уже написал в чём ваша проблема. Ссылку даже предоставил, где описано решение. Вот она, на случай, если вы не увидели мой прошлый пост. Вам нужно настроить IIS на загрузку профиля пользователя, для корректной работы LocalDB.



1



GENDALF_ISTARI

15 / 32 / 19

Регистрация: 20.08.2013

Сообщений: 740

08.02.2016, 20:09

 [ТС]

9

Ех Usaga я не пойму как это делать
ведь понять можно увидив разницу между
VS2015 локальному подключению к базе в Web.config

и

Подключению в IIS в строке подключения

Я не пойму эту разницу куда строку ту пихать в той статье
в IIS ругаеться

как же ту строку пихать ?

Ну вот IIS->Строки подключения

XML
1
2
3
4
<connectionStrings>
    <add name="DB_Context" connectionString="Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename='|DataDirectory|Database_base.mdf';Integrated Security=True"
 providerName="System.Data.SqlClient"/>
  </connectionStrings>

Куда мне тулить эту строку ?

XML
1
2
3
<add name="DefaultAppPool">
        <processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
 </add>

если я шас сделаю так пул .NET v4.5 Classic

XML
1
2
3
4
5
6
7
<connectionStrings>
    <add name="DB_Context" connectionString="Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename='|DataDirectory|Database_base.mdf';Integrated Security=True"
 providerName="System.Data.SqlClient"/>
<add name=".NET v4.5 Classic">
        <processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
 </add>
  </connectionStrings>

то IIS->Строки подключения
скажут ошибку

и куда это тулить в той статье ?

хоть пример правильного подключения IIS есть ?



0



Эксперт .NET

11074 / 7638 / 1178

Регистрация: 21.01.2016

Сообщений: 28,682

08.02.2016, 20:23

10

Изменения нужно внести в файл C:WindowsSystem32inetsrvconfigapplicationHost.config. После этого ещё нужно будет дать пользователю, из под которого работает приложение, права на чтениезапись файла базы данных.

Добавлено через 1 минуту
В статье, что по ссылке доступна, всё это написано. Внимательнее читайте.



1



GENDALF_ISTARI

15 / 32 / 19

Регистрация: 20.08.2013

Сообщений: 740

09.02.2016, 10:10

 [ТС]

11

Нашол участок в файле %SystemRoot%inetsrvconfigapplicationHost.config

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
<applicationPools>
            <add name="DefaultAppPool" />
            <add name="Classic .NET AppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" />
            <add name=".NET v2.0 Classic" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" />
            <add name=".NET v2.0" managedRuntimeVersion="v2.0" />
            <add name=".NET v4.5 Classic" managedRuntimeVersion="v4.0" managedPipelineMode="Classic" />
            <add name=".NET v4.5" managedRuntimeVersion="v4.0" />
            <add name="vitaly-tornado.zapto.org" />
            <add name="test-host.zapto.org" />
            <applicationPoolDefaults managedRuntimeVersion="v4.0">
                <processModel identityType="ApplicationPoolIdentity" />
            </applicationPoolDefaults>
        </applicationPools>

добавив ( loadUserProfile=»true» setProfileEnvironment=»true»)
и мне что изменить на теге applicationPoolDefaults

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
<applicationPools>
            <add name="DefaultAppPool" />
            <add name="Classic .NET AppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" />
            <add name=".NET v2.0 Classic" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" />
            <add name=".NET v2.0" managedRuntimeVersion="v2.0" />
            <add name=".NET v4.5 Classic" managedRuntimeVersion="v4.0" managedPipelineMode="Classic" />
            <add name=".NET v4.5" managedRuntimeVersion="v4.0" />
            <add name="vitaly-tornado.zapto.org" />
            <add name="test-host.zapto.org" />
            <applicationPoolDefaults managedRuntimeVersion="v4.0">
                <processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
            </applicationPoolDefaults>
        </applicationPools>

Или на теге .NET v4.5 Classic их добавить

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
<applicationPools>
            <add name="DefaultAppPool" />
            <add name="Classic .NET AppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" />
            <add name=".NET v2.0 Classic" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" />
            <add name=".NET v2.0" managedRuntimeVersion="v2.0" />
            <add name=".NET v4.5 Classic" identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" managedRuntimeVersion="v4.0" managedPipelineMode="Classic" />
            <add name=".NET v4.5" managedRuntimeVersion="v4.0" />
            <add name="vitaly-tornado.zapto.org" />
            <add name="test-host.zapto.org" />
            <applicationPoolDefaults managedRuntimeVersion="v4.0">
                <processModel identityType="ApplicationPoolIdentity" />
            </applicationPoolDefaults>
        </applicationPools>

Еще вопрос на счет самой строки в проекте Web.Config
она правильна ?

XML
1
2
3
4
<connectionStrings>
    <add name="DB_Context" connectionString="Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename='|DataDirectory|Database_base.mdf';Integrated Security=True"
 providerName="System.Data.SqlClient"/>
  </connectionStrings>

И что менять и как ?

Добавлено через 13 часов 30 минут
Это не помогло, доступ безопасности я разрешил, для IIS каталога проекта



0



GENDALF_ISTARI

15 / 32 / 19

Регистрация: 20.08.2013

Сообщений: 740

11.02.2016, 23:11

 [ТС]

12

Ошибка Local Database Runtime IIS MVC

файле %SystemRoot%inetsrvconfigapplicationHost.config
изменение не действует

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
<applicationPools>
            <add name="DefaultAppPool" />
            <add name="Classic .NET AppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" />
            <add name=".NET v2.0 Classic" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" />
            <add name=".NET v2.0" managedRuntimeVersion="v2.0" />
            <add name=".NET v4.5 Classic" managedRuntimeVersion="v4.0" managedPipelineMode="Classic" />
            <add name=".NET v4.5" managedRuntimeVersion="v4.0" />
            <add name="vitaly-tornado.zapto.org" />
            <add name="test-host.zapto.org" />
            <applicationPoolDefaults managedRuntimeVersion="v4.0">
                <processModel identityType="ApplicationPoolIdentity" />
            </applicationPoolDefaults>
        </applicationPools>

Как решить проблему товарищи ?

Миниатюры

Ошибка Local Database Runtime. Невозможно создать автоматический экземпляр
 



0



15 / 32 / 19

Регистрация: 20.08.2013

Сообщений: 740

21.02.2016, 18:51

 [ТС]

13

Тема закрыта вот мой пример
инструкция решения этой проблемы
пользуйтесь )))



0



  • Remove From My Forums
  • Question

  • From Robert Luongo @RobertLuongo via Twitter

    I got stuck at the point when you need to run the update-database command on the NuGet Package Console. I have followed all exact instructions, and the default connection string that has been created is as follows. <add name=»DefaultConnection»
    connectionString=»Data Source=(LocalDb)MSSQLLocalDB;AttachDbFilename=|DataDirectory|aspnet-ContactManager-20160302022257.mdf;Initial Catalog=aspnet-ContactManager-20160302022257;Integrated Security=True» providerName=»System.Data.SqlClient»
    />.

    When I run the update-database command I get the following error: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct
    and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 — Local Database Runtime error occurred. The specified LocalDB instance does not exist. Using NuGet Package Manager 3.3.0 with Visual Studio 2015 Community
    Version 14.0.24720.00.

    EDIT: This is now sorted !! :)

    Issue was as you anticipated the NuGet Package Manager was not able to create the instance specified in the DefaultConnection string. Data Source=(LocalDb)MSSQLLocalDB. I changed it to Data Source=(LocalDB)v11.0 and it now works, probably this is how the
    instance should be specified when using SQL Express Edition ??

    Thanks,
    @AzureSupport


    Thiene Schmidt

    • Edited by

      Thursday, March 3, 2016 11:33 AM

Answers

  • Yes SQL Express Edition will throw an instance specific error when using Data Source=(LocalDb)MSSQLLocalDB
    in connection string, the only way I got it to work was by changing it to 
    (LocalDB)v11.0 , so is that
    actually an SQL Express Edition issue ??? or is it caused by something else ?? thanks !!

    • Proposed as answer by
      Casey KarstMicrosoft employee
      Friday, March 4, 2016 11:52 PM
    • Marked as answer by
      Casey KarstMicrosoft employee
      Monday, March 7, 2016 3:54 PM

mnepoh

Описание: Необработанное исключение при выполнении текущего веб-запроса. Изучите трассировку стека для получения дополнительных сведений о данной ошибке и о вызвавшем ее фрагменте кода.

Сведения об исключении: System.Data.SqlClient.SqlException: При установлении соединения с SQL Server произошла ошибка, связанная с сетью или с определенным экземпляром. Сервер не найден или недоступен. Убедитесь, что имя экземпляра указано правильно и что на SQL Server разрешены удаленные соединения. (provider: SQL Network Interfaces, error: 50 — Произошла ошибка Local Database Runtime.Невозможно создать автоматический экземпляр. Дополнительные сведения об ошибке см. в журнале событий приложений Windows.)

Ошибка возникает даже если подключаться к полноценному SQL server.


  • Вопрос задан

    более трёх лет назад

  • 14308 просмотров

Пригласить эксперта

Так, собственно, все возможные причины уже описаны. Что вы хотите ещё узнать.
Проверьте connection string. Если стоит SQL Server, то проверьте, включен ли браузер и настроены удаленные соединения.
Но скорее всего проблема в строке подключения.

Ответ нашел только тут

Если в кратце, то помогло только изменение Application Pool Identity в LocalSystem.

Если сервер ваш и IIS в ваших руках, то проблем нет, а вот если где-то хоститесь, то на практике не могу подсказать.


  • Показать ещё
    Загружается…

09 февр. 2023, в 14:22

1500 руб./за проект

09 февр. 2023, в 13:58

2000 руб./за проект

09 февр. 2023, в 13:28

777 руб./за проект

Минуточку внимания

Я пытаюсь создать веб-приложение ASP.NET MVC 5 с файлом MyDatabase.mdf в папке App_Data. У меня установлен SQL Server 2014 Express с экземпляром LocalDb. Я могу редактировать таблицы базы данных с помощью Server Explorer, однако, когда я отлаживаю приложение и перехожу на страницу, где нужна база данных, я получаю следующую ошибку.

При установлении соединения с SQL Server возникла связанная с сетью или конкретная ошибка экземпляра. Сервер не найден или не был доступен. Проверьте правильность имени экземпляра и настройте SQL Server для удаленного подключения. (провайдер: Сетевые интерфейсы SQL, ошибка: 50 — Произошла ошибка локальной базы данных. Невозможно создать автоматический экземпляр. См. журнал событий приложения Windows для получения подробных сведений об ошибке.

Итак, я посмотрел в средстве просмотра событий в разделе Application и снова вижу одно предупреждение снова и снова.

Недопустимый каталог, предназначенный для кэширования сжатого содержимого. C:UsersUser1AppDataLocalTempiisexpressIIS Временные сжатые файлы Clr4IntegratedAppPool. Статическое сжатие отключается.

Поэтому я попытался перезагрузить сервер, но все равно не пошел. Такая же ошибка 50, как и раньше.

Я создал класс под Models, где у меня есть класс под названием Post.

namespace MyApplication.Models
{
    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
    }

    public class MyDatabase : DbContext
    {
        public DbSet<Post> Posts { get; set; }
    }
}

У меня также есть настройка Controller, чтобы перечислять сообщения из MyDatabase.

namespace MyApplication.Controllers
{
    public class PostsController : Controller
    {
        private MyDatabase db = new MyDatabase();

        // GET: Posts
        public ActionResult Index()
        {
            return View(db.Posts.ToList());
        }
    }

В моем файле web.config строка подключения выглядит так:

<connectionStrings>
    <add name="DefaultConnection" 
         connectionString="Data Source=(LocalDB)v12.0;AttachDbFilename=|DataDirectory|MyDatabase.mdf;Integrated Security=True" 
         providerName="System.Data.SqlClient" />
</connectionStrings>

Я пробовал предлагаемое предложение здесь, но это не сработало. Также попробовал этот.

Я также замечаю, что экземпляр MyDatabase отключается после запуска приложения. Если я обновляю базу данных с помощью Server Explorer в Visual Studio, я могу просмотреть таблицы.

Как я могу подключиться к базе данных и отредактировать ее в Visual Studio 2013, но когда я отлаживаю приложение, он не может подключиться к базе данных?

score:127

Accepted answer

Breaking Changes to LocalDB: Applies to SQL 2014; take a look over this article and try to use (localdb)mssqllocaldb as server name to connect to the LocalDB automatic instance, for example:

<connectionStrings>
  <add name="ProductsContext" connectionString="Data Source=(localdb)mssqllocaldb; 
  ...

The article also mentions the use of 2012 SSMS to connect to the 2014 LocalDB. Which leads me to believe that you might have multiple versions of SQL installed — which leads me to point out this SO answer that suggests changing the default name of your LocalDB «instance» to avoid other version mismatch issues that might arise going forward; mentioned not as source of issue, but to raise awareness of potential clashes that multiple SQL version installed on a single dev machine might lead to … and something to get in the habit of in order to avoid some.

Another thing worth mentioning — if you’ve gotten your instance in an unusable state due to tinkering with it to try and fix this problem, then it might be worth starting over — uninstall, reinstall — then try using the mssqllocaldb value instead of v12.0 and see if that corrects your issue.

score:1

My issue was that i had multiple versions of MS SQL express installed. I went to installation folder C:/ProgramFiles/MicrosoftSQL Server/ where i found
3 versions of it. I deleted 2 folders, and left only MSSQL13.SQLEXPRESS which solved the problem.

score:2

In my case, we had several projects in one solution and had selected a different start project than in the package manager console when running the «Update-Database» Command with Code-First Migrations.
Make sure to select the proper start project.

score:2

I have solved above problem Applying below steps

enter image description here

And after you made thses changes, do following changes in your web.config

 <add name="DefaultConnection" connectionString="Data Source=(LocalDb)v12.0;AttachDbFilename=|DataDirectory|aspnet-Real-Time-Commenting-20170927122714.mdf;Initial Catalog=aspnet-Real-Time-Commenting-20170927122714;Integrated Security=true" providerName="System.Data.SqlClient" />

score:3

All PLEASE note what Tyler said

Note that if you want to edit this file make sure you use a 64 bit text editor like notepad. If you use a 32 bit one like Notepad++ it will automatically edit a different copy of the file in SysWOW64 instead. Hours of my life I won’t get back

score:4

Final Solution for this problem is below :

  1. First make changes in applicationHost config file. replace below string setProfileEnvironment=»false» TO setProfileEnvironment=»true»

  2. In your database connection string add below attribute : Integrated Security = SSPI

score:4

I ran into the same problem. My fix was changing
<parameter value="v12.0" />
to
<parameter value="mssqllocaldb" />
into the «app.config» file.

score:8

maybe this error came because this version of Sql Server is not installed

connectionString="Data Source=(LocalDB)v12.0;....

and you don’t have to install it

the fastest fix is to change it to any installed version you have

in my case I change it from v12.0 to MSSQLLocalDB

score:18

An instance might be corrupted or not updated properly.

Try these Commands:

C:>sqllocaldb stop MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" stopped.
 
C:>sqllocaldb delete MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" deleted.
 
C:>sqllocaldb create MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" created with version 13.0.1601.5.
 
C:>sqllocaldb start MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" started.

score:25

To begin — there are 4 issues that could be causing the common LocalDb SqlExpress Sql Server connectivity errors SQL Network Interfaces, error: 50 - Local Database Runtime error occurred, before you begin you need to rename the v11 or v12 to (localdb)mssqllocaldb

Possible Issues
  • You don’t have the services running
  • You don’t have the firelwall ports here
    configured
  • Your install has and issue/corrupt (the steps below help give you a nice clean start)
  • You did not rename the V11 or 12 to mssqllocaldb
 \ rename the conn string from v12.0 to MSSQLLocalDB -like so-> 
 `<connectionStrings>
      <add name="ProductsContext" connectionString="Data Source= (localdb)mssqllocaldb; 
      ...`

I found that the simplest is to do the below — I have attached the pics and steps for help.

First verify which instance you have installed, you can do this by checking the registry& by running cmd

 1. `cmd> Sqllocaldb.exe i` 
 2. `cmd> Sqllocaldb.exe s "whicheverVersionYouWantFromListBefore"` 
if this step fails, you can delete with option `d` cmd> Sqllocaldb.exe d "someDb"
 3. `cmd> Sqllocaldb.exe c "createSomeNewDbIfyouWantDb"` 
 4. `cmd> Sqllocaldb.exe start "createSomeNewDbIfyouWantDb"`

SqlLOCALDb_edited.png


ADVANCED Trouble Shooting Registry configurations

Edit 1, from requests & comments: Here are the Registry path for all versions, in a generic format to track down the registry

Paths

// SQL SERVER RECENT VERSIONS
HKEY_LOCAL_MACHINESOFTWAREMicrosoftMicrosoft SQL Server(instance-name)

// OLD SQL SERVER
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesMSSQLServer
HKEY_LOCAL_MACHINESOFTWAREMicrosoftMSSQLServer
// SQL SERVER 6.0 and above.

HKEY_LOCAL_MACHINESystemCurrentControlSetServicesMSDTC
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesSQLExecutive
// SQL SERVER 7.0 and above

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesSQLServerAgent
HKEY_LOCAL_MACHINESoftwareMicrosoftMicrosoft SQL Server 7
HKEY_LOCAL_MACHINESoftwareMicrosoftMSSQLServ65

Searching

SELECT registry_key, value_name, value_data  
FROM sys.dm_server_registry  
WHERE registry_key LIKE N'%SQLAgent%';

or Run this in SSMS Sql Management Studio, it will give a full list of all installs you have on the server

DECLARE     @SQL VARCHAR(MAX)
SET         @SQL = 'DECLARE @returnValue NVARCHAR(100)'
SELECT @SQL = @SQL + CHAR(13) + 'EXEC   master.dbo.xp_regread

 @rootkey      = N''HKEY_LOCAL_MACHINE'',
 @key          = N''SOFTWAREMicrosoftMicrosoft SQL Server' + RegPath + 'MSSQLServer'',
 @value_name   = N''DefaultData'',
 @value        = @returnValue OUTPUT; 

 UPDATE #tempInstanceNames SET DefaultDataPath = @returnValue WHERE RegPath = ''' + RegPath + '''' + CHAR(13) FROM #tempInstanceNames 

 -- now, with these results, you can search the reg for the values inside reg
 EXEC (@SQL)
 SELECT      InstanceName, RegPath, DefaultDataPath
 FROM        #tempInstanceNames

Trouble Shooting Network configurations

SELECT registry_key, value_name, value_data  
FROM sys.dm_server_registry  
WHERE registry_key LIKE N'%SuperSocketNetLib%';  

score:36

I usually fix this errore following this msdn blog post Using LocalDB with Full IIS

This requires editing applicationHost.config file which is usually located in C:WindowsSystem32inetsrvconfig. Following the instructions from KB 2547655 we should enable both flags for Application Pool ASP.NET v4.0, like this:

<add name="ASP.NET v4.0" autoStart="true" managedRuntimeVersion="v4.0"     managedPipelineMode="Integrated">
    <processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
</add>

score:42

Running this:

sqllocaldb create «v12.0»

From cmd prompt solved this for me…

Related Query

  • SQL Network Interfaces, error: 50 — Local Database Runtime error occurred. Cannot create an automatic instance
  • The page cannot be displayed because an internal server error has occurred on server
  • Unable to connect to localDB in VS2012 – «A network-related or instance-specific error occurred while establishing a connection to SQL Server…»
  • Connecting to local SQL Server database using C#
  • Local database without sql server
  • How can I run C# app which contains local SQL Server database on another computer?
  • SQL logic error or missing database no such table
  • Using Hangfire, connection string given in Startup.cs throws Cannot attach file as database error
  • Visual Studio is trying to connect SQL database while loading a solution. Gives error: Cannot open database requested by the login
  • Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator
  • Printing a Local Report without Preview — Stream size exceeded or A generic error occurred in GDI+ C#
  • Azure Kubernetes .NET Core App to Azure SQL Database Intermittent Error 258
  • How to create a simple Local SQL database & insert values into it using C#?
  • Best way to sync remote SQL Server database with local SQL Server Compact database?
  • Cannot detect SQL error when using ExecuteNonQuery()
  • Occasional Exceptions: «A network-related or instance-specific error occurred while establishing a connection to SQL Server»
  • Creating custom assembly in SQL Server throwing assembly not found in database error
  • runtime code compilation gives error — process cannot access the file
  • Error :RESTORE cannot process database ‘Test_DB’ because it is in use by this session
  • Outlook Addin Error: Not loaded. A runtime error occurred during loading of COM add-in
  • SQL query error — «Column cannot be null»
  • How to create a setup.exe file using InstallShield LE for a Visual Studio 2012 Windows Forms Application with SQL Server 2012 Local Database
  • Changing from local database to SQL Server hosted on a server
  • A generic error occurred in GDI+, JPEG Image to MemoryStream
  • I get a «An attempt was made to load a program with an incorrect format» error on a SQL Server replication project
  • Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away
  • Cannot open database «test» requested by the login. The login failed. Login failed for user ‘xyzASPNET’
  • Cannot drop database because it is currently in use
  • Windows service on Local Computer started and then stopped error
  • An error occurred attempting to determine the process id of the DNX process hosting your application

More Query from same tag

  • What’s a good threadsafe singleton generic template pattern in C#
  • How do I use SHA-512 with Rfc2898DeriveBytes in my salt & hash code?
  • How to change position of inherited items in an Inherited user control
  • Any ORMs that work with MS-Access (for prototyping)?
  • Get Length of Data Available in NetworkStream
  • Use Dash (-) Character in enum parameter
  • How can I use Dependency Injection in a .Net Core ActionFilterAttribute?
  • C# memory profile
  • WPF Textbox and space character wrapping
  • UseSpaPrerendering being deprecated from .net core 3.0 onwards, what is the alternative?
  • How Can I Add a Unit Test Project to an Existing MVC3 Application (from empty template)
  • Which .NET library has copy-on-write collections?
  • Amazon S3 upload with public permissions
  • ComboBox refreshes ListBox
  • Any way to run .net core web app without debug mode?
  • .NET 4.0 C# initialization string does not conform Login error
  • Is ‘#IF DEBUG’ deprecated in modern programming?
  • What is the MVC Futures Library?
  • Enumerate JumpList recent files?
  • user control not rendering content of ascx
  • error creating the web proxy specified in the ‘system.net/defaultproxy’ configuration section
  • How to call a Controller method which is accepting two models?
  • Overloading two functions with object and list<object> parameter
  • How to find inactive objects using GameObject.Find(» «) in Unity3D?
  • tabbing in C# resource file
  • C# How to XOR all int elements of an array after reading from console?
  • Wire up MiniProfiler to ASP.NET Core Web API Swagger
  • The model’s Hidden bool field remains False after it was set True in the controller
  • Why is SynchronizationContext.Current null?
  • Adding SOAP:HEADER username and password with WSE 3.0

Понравилась статья? Поделить с друзьями:
  • Error 404 санс история
  • Error 404 санс вики
  • Error 404 санс арт
  • Error 404 рисунок
  • Error 404 примеры