1
Running the query gives a Timeout Sql Server error:
Connection Method:
public SqlDataReader GetDataReader(string comando)
{
SqlConnection conn = criaConexao();
// Cria Comando
SqlCommand cmd = new SqlCommand(comando, conn);
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 0;
foreach (SqlParameter oP in alParameters)
{
cmd.Parameters.AddWithValue(oP.ParameterName, oP.Value);
}
try
{
conn.Open();
var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
catch (Exception ex)
{
throw ex;
}
finally
{
//conn.Close();
}
}
Method populating the model:
public List<MeuModelo> SelectProduto(MeuModelo meuModel)
{
try
{
StringBuilder sb = new StringBuilder();
DataAcess dataAcces = new DataAcess();
List<MeuModelo> lModel = new List<MeuModelo>();
sb.Append(" SELECT ");
sb.Append(" prd.ProductID, prd.ProductName, cat.Nome");
sb.Append(" FROM");
sb.Append(" Products as prd (NOLOCK)");
sb.Append(" INNER JOIN Categoria as cat (NOLOCK)");
sb.Append(" ON prd.ProductID = cat.ProductID");
sb.Append(" WHERE prd.ProductID = 1");
SqlDataReader dr = dataAcces.GetDataReader(sb.ToString());
if (dr.HasRows)
{
while (dr.Read())
{
MeuModelo meuModelo = new MeuModelo();
meuModelo.ProductID = Convert.ToInt32(dr["ProductID"]);
meuModelo.Nome = dr["Nome"];
lModel.Add(meuModelo);
}
}
return lModel ;
}
catch(Exception ex)
{
throw new Exception("Erro na query que seleciona produto categoria: " + ex.Message.ToString());
}
}
The query when executed in sql server management studio is very fast and returns 1 record only.
This query is used by a web api and after a 3 calls is returned Sql Server Timeout: "Erro na query que seleciona produto categoria"
.
How to solve this Timeout problem considering that the execution of the query is fast and simple ?
You need to close the connection, the problem is there, returning Datareader to the other layer of your application. Why don’t you populate the list and return it to your Selectproduct ?
– Thiago Loureiro