1

Estou com uma aplicação finalizada desenvolvida em C# utilizando Asp Net MVC. No meu servidor local a aplicação se conecta ao banco de dados que está no servidor da empresa que trabalho, portanto ao colocar a aplicação pra rodar no provedor da Rede Host não esta conseguindo inicializar o banco, da um erro exibindo a seguinte mensagem: An error occurred while executing the command definition. See the inner exception for details.

Ele recupera o backup tudo ok, portanto não inicializa o banco, aqui está a parte do código que configuro toda essa parte, lembrando que as credencias apaguei deixando tudo vazio:

public NFeWebContext()
            : base($"Data Source=;Initial Catalog=BD{HttpContext.Current.User.Identity.Name};Persist Security Info=True;User ID =;Password=;MultipleActiveResultSets=True;App=EntityFramework providerName=System.Data.SqlClient")
        {
            //$"Data Source=;Initial Catalog=b;Integrated Security=True; User ID = ;Password=; MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient"
            //$"Data Source=;Initial Catalog=BD{HttpContext.Current.User.Identity.Name};Persist Security Info=True;User ID =;Password=;MultipleActiveResultSets=True;App=EntityFramework providerName=System.Data.SqlClient"
            SqlConnection cnn = new SqlConnection($"Data Source=;Initial Catalog=MASTER;Persist Security Info=True;User ID =;Password=;MultipleActiveResultSets=True;App=EntityFramework providerName=System.Data.SqlClient");
            cnn.Open();

            if (!System.Data.Entity.Database.Exists($"Data Source=;Initial Catalog=BD{HttpContext.Current.User.Identity.Name};Persist Security Info=True;User ID =;Password=;MultipleActiveResultSets=True;App=EntityFramework providerName=System.Data.SqlClient"))
            {
                SqlCommand cmdRestore = new SqlCommand();
                cmdRestore.Connection = cnn;

                cmdRestore.CommandText = $@"USE MASTER;
                                              RESTORE DATABASE [BD{HttpContext.Current.User.Identity.Name}] 
                                              FROM DISK = 'DIRETORIO DO BACKUP'
                                              WITH                                        
                                              Move 'BD' TO 'DIRETORIO DO BACKUP', 
                                              Move 'BD_log' TO 'DIRETORIO DO BACKUP',
                                              Replace, RECOVERY";
                cmdRestore.ExecuteNonQuery();
                cnn.Close();
                //  bdcliente.Open();
            }
        }

E aqui está o erro que o inner exception exibe:

System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception: The wait operation timed out --- End of inner exception stack trace --- at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error) at System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync() at System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket() at System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer() at System.Data.SqlClient.TdsParserStateObject.TryReadByte(Byte& value) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c) at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) --- End of inner exception stack trace --- at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues) at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6() at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation) at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0() at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at
4
  • 1
    E o que diz a inner exception? Commented 16/05/2018 às 18:52
  • Não esta retornando a inner exception, esse é um dos fatos que deixa ainda mais complicado!
    – WPfan
    Commented 16/05/2018 às 18:54
  • Não está retornando, ou você não está conseguindo ver? Commented 16/05/2018 às 19:22
  • @LeandroAngelo consegui retornar o erro aqui, vou editar a pergunta e inclui-lo, veja lá e me diz se tu tem uma ideia do que esta acontecendo
    – WPfan
    Commented 16/05/2018 às 19:23

1 Resposta 1

1

Pelo erro: "The timeout period elapsed prior to completion of the operation or the server is not responding...."

Trata-se de uma consulta/comando que leva mais tempo para ser executada do que esperado e analisando seu SQL o comando que está sendo utilizado trata-se de um restore de uma base de dados.

Então provavelmente a execução dessa operação é cara e estora o tempo limite.

Uma alternativa seria aumentar o limite em sua conexão, exemplo:

 cmdRestore.CommandTimeout = 300;
1
  • Muito obrigado, realmente é algo nesse sentido que está ocorrendo, e com a sua resposta eu conseguir entender aqui o que pode ser feito pra resolver junto com a sua sugestão!
    – WPfan
    Commented 17/05/2018 às 11:22

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .