How to make second select in "Read"?

Asked

Viewed 44 times

0

Here is the code:

public FileContentResult Foto()
        {
            byte[] byte_image = null;
            string query = "SELECT * FROM Tabela WHERE Coluna = @Parameter";
            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            using (var command = new SqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("@Parameter", User.Identity.Name);
                connection.Open();
                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        if (!Convert.IsDBNull(reader["Byte_Image"]))
                        {
                            byte_image = (byte[])reader["Byte_Image"];
                        }
                        else
                        {
                            //Segundo select aqui
                            string query = "SELECT * FROM Tabela1 WHERE Coluna1 = @Parameter";
                        }
                    }
                }
            }
            return new FileContentResult(byte_image, "image/jpeg");
        }

On the line else how to make second select with Reader ?

1 answer

0


There is, in this case, no imperative need to use the same object IDataReader, can therefore create a new object IDataReader within the scope of else.

Your code would look like this:

public FileContentResult Foto()
{
    byte[] byte_image = null;
    string query = "SELECT * FROM Tabela WHERE Coluna = @Parameter";
    using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
    using (var command = new SqlCommand(query, connection))
    {
        command.Parameters.AddWithValue("@Parameter", User.Identity.Name);
        connection.Open();
        using (var reader = command.ExecuteReader())
        {
            if (reader.Read())
            {
                if (!Convert.IsDBNull(reader["Byte_Image"]))
                {
                    byte_image = (byte[])reader["Byte_Image"];
                }
                else
                {
                    //Segundo select aqui
                    string query = "SELECT * FROM Tabela1 WHERE Coluna1 = @Parameter";

                    using (var command2 = new SqlCommand(query, connection))
                    {
                      command2.Parameters.AddWithValue("@Parameter", User.Identity.Name);

                      using (var reader2 = command2.ExecuteReader()) {

                        //OPERAÇÃO SOBRE O reader2

                      }
                    }
                }
            }
        }
    }
    return new FileContentResult(byte_image, "image/jpeg");
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.