Large bulk inserts cause transaction aborts or timeouts - c#

Problem
When doing a bulk insert with several hundred thousand rows over two databases (programmatically, same instance, same schema) and about 17 tables per database, I nearly always receive a Transcaction Aborted or a Timeout Expired exception.
How
Using a EntityFramework 6 data context, I run a SqlCommand on the database.
using (var tran = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
{
context.Database.ExecuteSqlCommand(
"BULK INSERT " + table +
" FROM '" + Directory +
table + ".csv' WITH ( DATAFILETYPE = 'widechar', FIRSTROW = 2, FIELDTERMINATOR = '[TERM]', ERRORFILE = '" +
Logfile + DateTime.Now.ToString(#"yyyy-MM-dd") + "-R" + DateTime.Now.Second + DateTime.Now.Millisecond +
".txt', ROWTERMINATOR = '\n', KEEPNULLS, TABLOCK )");
tran.Complete();
}
Setting timeout values
To combat the problems I've been facing I have set both Command and Transaction timeouts to eighteen minutes. Either exception occurs long before said eighteen minutes have passed.
context.Database.CommandTimeout = 1080;
TransactionOptions transactionOptions = new TransactionOptions();
transactionOptions.Timeout = TimeSpan.FromMinutes(18);
Full exceptions
System.Data.SqlClient.SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
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.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(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.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass59.<ExecuteStoreCommand>b__58()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass59.<ExecuteStoreCommand>b__57()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreCommand(TransactionalBehavior transactionalBehavior, String commandText, Object[] parameters)
at System.Data.Entity.Internal.InternalContext.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
at System.Data.Entity.Database.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
at System.Data.Entity.Database.ExecuteSqlCommand(String sql, Object[] parameters)
at MyProject.Updaters.MSSQL.Csv.ImportCsvFiles() in c:\Users\MyUser\Desktop\MyProject2\XMLtoDBcron\Updaters\MSSQL\Csv.cs:line 48
ClientConnectionId:fef47d9c-3e13-444f-939b-f9bd570abb36
+
System.Transactions.TransactionAbortedException: The transaction has aborted. ---> System.TimeoutException: Transaction Timeout
--- End of inner exception stack trace ---
at System.Transactions.TransactionStateAborted.BeginCommit(InternalTransaction tx, Boolean asyncCommit, AsyncCallback asyncCallback, Object asyncState)
at System.Transactions.CommittableTransaction.Commit()
at System.Transactions.TransactionScope.InternalDispose()
at System.Transactions.TransactionScope.Dispose()
at MyProject.Updaters.MSSQL.Csv.InsertCsvData() in c:\Users\MyUser\Desktop\MyProject2\XMLtoDBcron\Updaters\MSSQL\Csv.cs:line 109
at MyProject.Updaters.MSSQL.Csv.ImportCsvFiles() in c:\Users\MyUser\Desktop\MyProject2\XMLtoDBcron\Updaters\MSSQL\Csv.cs:line 74
What to do
I couldn't find any settings or similar within SQL Server (using SSMS). Any extra data you request to aid in providing an answer will be given.

Regarding timout during sql commands execution I would recommend you to set CommandTimeout via ObjectContext wrapped within DbContext:
((IObjectContextAdapter)context).ObjectContext.CommandTimeout = 1080;
This approach always worked for me.

Related

EFMigrationsHistory table is empty

Im creating database in debug. When database not exist, i create new one:
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetService<LolDbContext>();
context?.Database.EnsureCreated();
if (context.Database.CanConnect())
{
context.Database.Migrate();
}
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger>();
logger.Error($"Exception while migrating db: {ex}");
}
}
host.Run();
}
After app starts i get this exception:
[11:47:10 [Error] Exception while migrating db: Microsoft.Data.SqlClient.SqlException (0x80131904): There is already an object named 'Table' in the database.
at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean isAsync, Int32 timeout, Boolean asyncWrite)
at Microsoft.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String methodName)
at Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
at eSportsLab.LeagueOfLegends.Api.Frontend.Program.Main(String[] args) in D:\repos\lol-sumeron-app\LeagueOfLegends\Presentation\eSportsLab.LeagueOfLegends.Api.Frontend\Program.cs:line 32
ClientConnectionId:00b6a255-f82d-49b2-adf6-23b83d0aeb1b
Error Number:2714,State:6,Class:16
When i go to SSMS i can see created database (with tables, data as expected), but table [__EFMigrationsHistory] is empty. In another database everything works fine:
My question is, why EF dont tracking migrations when i initialize DB like that?
Shortly, you should not use EnsureCreated if you are using migrations.
Apply migrations at runtime section of the official EF Core documentation contains the following Warning:
Don't call EnsureCreated() before Migrate(). EnsureCreated() bypasses Migrations to create the schema, which causes Migrate() to fail.

The timeout period elapsed prior to completion of the operation or the server is not responding. with showing package path

I am uploading a mdb file from asp.net upload control into my sql server database.
When I am uploading file it is calling a stored procedure from my database in which I m executing my SSIS packages. Whenever I am calling my stored procedure after few seconds I m getting the exception with showing the path of my packages.
$exception {"Execution Timeout Expired. The timeout period elapsed
prior to completion of the operation or the server is not
responding.\r\ndtexec /F
\"C:\DTSX\DTSXPackage\DTSXPackage\Package.dtsx\""} System.Data.SqlClient.SqlException
As I read for solution. Read about Command timeout property of SQL. But still issue is same.
When I m running stored procedure through SQL server it is running fine but when calling it through the asp.net code it giving exception.
stack trace -
>
StackTrace " at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 wrapCloseInAction)\r\n
at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n
at
System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject
stateObj, UInt32 error)\r\n at
System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync()\r\n
at
System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket()\r\n
at System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer()\r\n
at System.Data.SqlClient.TdsParserStateObject.TryReadByte(Byte&
value)\r\n at System.Data.SqlClient.TdsParser.TryRun(RunBehavior
runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady)\r\n at
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString, Boolean
isInternal, Boolean forDescribeParameterEncryption)\r\n 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)\r\n at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task,
Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)\r\n at
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1
completion, String methodName, Boolean sendToPipe, Int32 timeout,
Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)\r\n at
System.Data.SqlClient.SqlCommand.ExecuteNonQuery()\r\n at
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query,
QueryInfo queryInfo, IObjectReaderFactory factory, Object[]
parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object
lastResult)\r\n at
System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query,
QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[]
userArguments, ICompiledSubQuery[] subQueries)\r\n at
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression
query)\r\n at System.Data.Linq.DataContext.ExecuteMethodCall(Object
instance, MethodInfo methodInfo, Object[] parameters)\r\n at
DataAccessLayer.EspaceDatasetDataContext.ETL_IMPORT_09_01(Nullable1
userId, String clientMachineIP, String loadType, Nullable1 instId,
Nullable1 bIsIgnoreErrors, Nullable`1& rcout)
stored procedure calling method:-
public int? RunDTSxProcess(long userID, string clientMachineIP, string loadType, long instID, bool ignoreErrors)
{
try
{
int? result = 0;
var run = database.storedproc(userID, clientMachineIP, loadType, instID, ignoreErrors,ref result);
return result;
}
catch (Exception)
{
throw;
}
}
I think you may be looking to do something with MainContext for your linq to sql as detailed in this answer.
taken from the above answer:
using (MainContext db = new MainContext())
{
db.CommandTimeout = 3 * 60; // 3 Mins
}

How can f System.Data.Entity.Internal.InternalContext.SaveChanges()

I have a windows service that call a Web Service, then stored the information in my t-sql database. In my pc this service works, but in another pc with the same database I have this error:
[16:06:00] Teresa Gabriele: Errore saveLocalActivity: in System.Data.Entity.Internal.InternalContext.SaveChanges()
in System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
in System.Data.Entity.DbContext.SaveChanges()
in GestoreService.Manager.Impl.AttivitaManagerImpl.saveLocalActivity(LOCAL_PE_Attivita attivita, Boolean saving) in c:\Users\michele.castriotta\Source\Workspaces\Omniacare\software\exercise platform\GestoreService\GestoreService\Manager\Impl\AttivitaManagerImpl.cs:riga 25
[16:06:52] Teresa Gabriele: Errore isAttivitaXMedicoExist: in System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
in System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
in System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
in System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
in System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
in System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
in System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
in System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)
in System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
in System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
in System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass57.<ExecuteStoreCommand>b__56()
in System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
in System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass57.<ExecuteStoreCommand>b__55()
in System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
in System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreCommand(TransactionalBehavior transactionalBehavior, String commandText, Object[] parameters)
in System.Data.Entity.Internal.InternalContext.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
in System.Data.Entity.Database.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
in System.Data.Entity.Database.ExecuteSqlCommand(String sql, Object[] parameters)
in GestoreService.Manager.Impl.AttivitaManagerImpl.inserAttivitaXMedico(Int32 idAttivita, String codiceFiscaleOperatoreMedico, String username) in c:\Users\michele.castriotta\Source\Workspaces\Omniacare\software\exercise platform\GestoreService\GestoreService\Manager\Impl\AttivitaManagerImpl.cs:riga 192
This is the code:
_db.LOCAL_PE_Attivita.Add(attivita);
int result = _db.SaveChanges(); //LINE 25
if (result > 0)
return true;
The Question is unclear, but I think that error is not in the code.
The log tell that error is in save on DB, but if this application work only on your pc I think (probably) that related to different version of DB.
checks whether this is the problem

An error occurred while executing the command definition - WCF

I've updated my model and done rebuilding the project (as suggested by stackoverflow) but no benefit.
My ASP.NET wcf webservice is working fine on local host. But when I upload it to AppHarbor (free asp.net web hosting service) I get an exception (I'm calling like this http://pizzaapp.apphb.com/Service1.svc/Login/123/1) which I can't understand (shown below). This works perfectly on my localhost, so what's the problem after uploading?
Request Error The server encountered an error processing the request.
The exception message is 'An error occurred while executing the
command definition. See the inner exception for details.'. See server
logs for more details. The exception stack trace is:
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.ObjectQuery1.<>c__DisplayClass3.<GetResults>b__2()
at
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1
func, IDbExecutionStrategy executionStrategy, Boolean
startLocalTransaction, Boolean releaseConnectionOnSuccess) at
System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClass3.<GetResults>b__1()
at
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1
operation) at
System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1
forMergeOption) at
System.Data.Entity.Core.Objects.ObjectQuery1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Lazy1.CreateValue() at System.Lazy1.LazyInitValue() at
System.Lazy1.get_Value() at
System.Data.Entity.Internal.LazyEnumerator1.MoveNext() at
System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source)
at
System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.b__2[TResult](IEnumerable1
sequence) at
System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable1
query, Expression queryRoot) at
System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression
expression) at
System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression
expression) at
System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source) at
WcfServicePizza.Service1.Login(String phoneNo, String password) in
d:\temp\lmtrshzg.bwx\input\WcfServicePizza\Service1.svc.cs:line 37 at
SyncInvokeLogin(Object , Object[] , Object[] ) at
System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object
instance, Object[] inputs, Object[]& outputs) at
System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&
rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean
isOperationContextSet)
The code for the webservice interface
[OperationContract]
[WebInvoke(UriTemplate="SignUp",
Method="POST",
BodyStyle=WebMessageBodyStyle.WrappedRequest,
ResponseFormat=WebMessageFormat.Json,
RequestFormat=WebMessageFormat.Json)]
bool SignUp(Customer customer);
And code for its implementation running on the server currently is:
public bool Login(string phoneNo, string password)
{
decimal phoneNoDecimal = Decimal.Parse(phoneNo);
DatabasePizzaEntities db = new DatabasePizzaEntities();
Customer customer = db.Customers.Where(c => c.PhoneNo==phoneNoDecimal && c.Password == password).SingleOrDefault();
if (customer == null)
return false;
return true;
}
INNER EXCEPTION:
Data.SqlClient.SqlException (0x80131904): Invalid object name
'dbo.Customer'.\u000d\u000a at
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action1 wrapCloseInAction)\u000d\u000a at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1
wrapCloseInAction)\u000d\u000a at
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean
asyncClose)\u000d\u000a at
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady)\u000d\u000a at
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()\u000d\u000a
at System.Data.SqlClient.SqlDataReader.get_MetaData()\u000d\u000a at
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString)\u000d\u000a at
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader
ds)\u000d\u000a at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task,
Boolean asyncWrite)\u000d\u000a at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method)\u000d\u000a at
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior, String method)\u000d\u000a at
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior
behavior)\u000d\u000a at
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior
behavior)\u000d\u000a at
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c__DisplayClassb.<Reader>b__8()\u000d\u000a
at
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TInterceptionContext,TResult](Func1
operation, TInterceptionContext interceptionContext, Action1
executing, Action`1 executed)\u000d\u000a at
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand
command, DbCommandInterceptionContext interceptionContext)\u000d\u000a
at
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior
behavior)\u000d\u000a at
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior
behavior)\u000d\u000a at
System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior
behavior)\u000d\u000aClientConnectionId:2c6eb8fd-ce5b-4866-8dc7-5ff565fb11d5\u000d\u000aError
Number:208,State:1,Class:16"
The difference between local host and AppHarbor is which database you are connecting to.
The error message is:
An error occurred while executing the command definition
This is generally a problem between your database schema and your mapping files.
Is the database Schema In AppHarbor different from that in your local database?
This is "Invalid Object Name", either:
the Customer table is not there,
or it is not in the dbo schema,
or the user in the connection string does not have rights to access the table.

ExecuteQueryin linq :Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding

I got an error while executing the datacontext.ExecuteCommand(objectname)
Error:
System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated.
Sample code:
Datacontext context = new Datacontext();
tablename tb=new tablename();
string DeleteQuery="delete from table A";
context.ExecuteCommand<tb>(DeleteQuery);
DeleteQuery=string.empty;
string InsertQuery="Insert into table B(a,b,c,d)Select table from C Union All Select Table from D";
context.ExecuteCommand<tb>(InsertQuery);
InsertQuery=string.empty;
here while executing insert query i m getting an error System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated.
The error Page as below
Server Error in '/Portal' Application.
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
The statement has been terminated.
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.
Exception Details: System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
The statement has been terminated.
Source Error:
Line 914: where ft.IsDeleted = 0 and ym.IsDeleted = 0 and ym.IsApproved = 1");
Line 915:
Line 916: dc.ExecuteQuery(InsertCommand);
Line 917: InsertCommand = string.Empty;
Line 918:
Source File: d:\Website\IDCCircle_Staging\Portal\Default.aspx.cs Line: 916
Stack Trace:
[SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
The statement has been terminated.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +2062078
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +5050204
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +234
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2275
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +33
System.Data.SqlClient.SqlDataReader.get_MetaData() +86
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +311
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +987
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +162
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12
System.Data.Common.DbCommand.ExecuteReader() +12
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +1266
System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +113
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +344
System.Data.Linq.DataContext.ExecuteMethodCall(Object instance, MethodInfo methodInfo, Object[] parameters) +83
System.Data.Linq.DataContext.ExecuteQuery(String query, Object[] parameters) +265
_Default.NHPgridbind() in d:\Website\IDCCircle_Staging\Portal\Default.aspx.cs:916
_Default.Page_Load(Object sender, EventArgs e) in d:\Website\IDCCircle_Staging\Portal\Default.aspx.cs:97
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
If table C and D contain a lot of rows, it may just be taking longer to run the insert than the default command timeout (30 seconds). Add this line before your insert command:
context.CommandTimeout = 240 // set timeout to 4 minutes
By the way, you should be disposing of the context when you have finished with it. The easiest way to do this is:
using (Datacontext context = new Datacontext())
{
// your code goes here
}

Categories