2015-10-21 5 views
2

Я получаю сообщение об ошибке, ниже которой для жизни меня не могу решить. Я использую EF 6 с Identity 2, и он работал нормально несколько дней назад.EF 6 не используется строка подключения в Web.config

Вчера я выпустил VS 2015 и начал получать ошибку при публикации на тестовом сайте и локально. Это похоже на то, что EF ищет локальный экземпляр SQL Express, хотя Web.config настроен на использование сервера SQL 2014 Standard.

Здесь ошибка:

Server Error in '/' Application. 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: 26 - Error Locating Server/Instance Specified) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

SQLExpress database file auto-creation error:

The connection string specifies a local Sql Server Express instance using a database location within the application's App_Data directory. The provider attempted to automatically create the application services database because the provider determined that the database does not exist. The following configuration requirements are necessary to successfully check for existence of the application services database and automatically create the application services database:

If the application is running on either Windows 7 or Windows Server 2008R2, special configuration steps are necessary to enable automatic creation of the provider database. Additional information is available at: http://go.microsoft.com/fwlink/?LinkId=160102 . If the application's App_Data directory does not already exist, the web server account must have read and write access to the application's directory. This is necessary because the web server account will automatically create the App_Data directory if it does not already exist. If the application's App_Data directory already exists, the web server account only requires read and write access to the application's App_Data directory. This is necessary because the web server account will attempt to verify that the Sql Server Express database already exists within the application's App_Data directory. Revoking read access on the App_Data directory from the web server account will prevent the provider from correctly determining if the Sql Server Express database already exists. This will cause an error when the provider attempts to create a duplicate of an already existing database. Write access is required because the web server account's credentials are used when creating the new database. Sql Server Express must be installed on the machine. The process identity for the web server account must have a local user profile. See the readme document for details on how to create a local user profile for both machine and domain accounts.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[SqlException (0x80131904): 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: 26 - Error Locating Server/Instance Specified)] System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +92 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +285

Это строка соединения и EF в конфигурации Web.config:

<entityFramework> 
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> 
    <providers> 
    <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> 
    </providers> 
</entityFramework> 
<connectionStrings> 
    <add name="DefaultConnection" connectionString="Data Source=SQL5017.Smarterasp.net;Initial Catalog=DB_9CF975_moverlive;User Id=xxxxxxxxx;Password=xxxxxxx;" providerName="System.Data.SqlClient" /> 
</connectionStrings> 

я могу соединиться отлично к БД с помощью SQL Server Management Studio с над строкой соединения.

Что я должен искать?

+1

ли вы какие-либо исследования на твой собственный? Как (с помощью какого кода) вы пытаетесь установить соединение? –

+1

Установите точку останова перед тем, как ваш DbContext будет первым. Посмотрите на db.Database.Connection.ConnectionString –

ответ

0

После долгих отладки я нашел опечатку в namespace в Startup.Auth.cs

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

После имен была исправлена, все функционировало, как и планировалось :-)

2

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

public class ApplicationDbContext : IdentityDbContext<ApplicationUser> 
{ 
    public ApplicationDbContext() 
     : base("DefaultConnection", false) 
    { 
    } 

    // ... 
+0

Спасибо Стив.Я уже проверил контекст БД и проверяет в порядке: класс 'ApplicationDbContext общественности: IdentityDbContext { общественного ApplicationDbContext() : основание ("DefaultConnection", throwIfV1Schema ложь) { }' – Richard

+1

Что значение 'ApplicationDbContext.Database.Connection.ConnectionString'? – Fenton

+0

Не совсем уверен, как я могу проверить ценность этого. Не удается найти свойство ApplicationDbContext.Database.Connection.ConnectionString. – Richard

0

Ваша строка подключения выглядит нормально. Ошибка указывает на то, что в вашем файле web.config или коде есть что-то, что ищет каталог App_Data, который является странным. Попробуйте сделать поиск в своем решении для App_Data или | DataDirectory | ,

Похоже, Существует ссылка на папку App_Data где-то в коде или (LocalDB) или SqlExpress

+0

Спасибо, Самсур. Я искал их, но не нашел ссылки на них в решении. – Richard

0

Вы случайно не имеют Config Преобразовать файл, как Web.Debug.config, или Web.Release.confi g под вашим Web.config файл вы? Это может быть переписывание вашей строки подключения.

Обычно Config Transform-файлы выполняют свои преобразования при публикации сайта, но я не уверен, как они работают в некоторых режимах отладки, так как существует несколько режимов для проектов ASP, таких как IIS Express и Local IIS.

У меня это случилось со мной сегодня с файлом App.config, App.Debug.config переписывал мою строку подключения, я даже не заметил, что был файл App.Debug.config, пока я не расширил узел , У него была совершенно другая строка подключения.

+0

У меня есть оба преобразования конфигурации thiose, но ни один из них не содержит строк подключения. – Richard

Смежные вопросы