When ExecuteNonQuery(), my database gets locked but if I comment that part ExecuteReader works fine. How to avoid database getting locked? I know that first is a write into database when creating indexes and the second time is reading but there are cases when this code below works fine. I need that index to be created to gain speed. There are a lot of functions created this way to get the data from the database (which is a .rdb file) and there are times that some of them are not working
List<TargetedOutputRDB1> entityList = new List<TargetedOutputRDB1>();
//
DbDataReader reader = null;
SimulationRDB1 simulation = (SimulationRDB1)crash.Simulation;
DbConnection dbConnection = ((RDB1Connection)crash.DbConnection).DbProviderFactory.CreateConnection();
dbConnection.ConnectionString = crash.DbConnection.ConnectionString;
bool connectionWasClosed = (dbConnection.State == ConnectionState.Closed);
//
try
{
DbCommand dbCommand = dbConnection.CreateCommand();
dbCommand.Transaction = (((RDB1Connection)simulation.DbConnection).DbTransaction != null && ((RDB1Connection)simulation.DbConnection).DbTransaction.Connection == simulation.DbConnection ? ((RDB1Connection)simulation.DbConnection).DbTransaction : null); //must be set!
//
if (dbConnection.State == ConnectionState.Closed)
dbConnection.Open();
//
dbCommand.CommandText = string.Format("CREATE INDEX IF NOT EXISTS TOIndexSC ON TargetedOutputs (SimulationId, CrashId)");
dbCommand.ExecuteNonQuery();
dbCommand.CommandText = string.Format("SELECT * FROM TargetedOutputs WHERE SimulationId={0} AND CrashId={1}", ((SimulationRDB1)crash.Simulation).ID, crash.ID);
reader = dbCommand.ExecuteReader();
//
while (reader.Read())
{
long id = (long)reader["Id"];
TargetedOutputRDB1 entity = new TargetedOutputRDB1(simulation, id, reader, false);
entityList.Add(entity);
}
//
return entityList.ToArray();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (reader != null)
reader.Close();
//
if (connectionWasClosed)
dbConnection.Close();
//dbConnection.Dispose();
}