Object Reference not set to an instance of an Object in return from Procedure

Asked

Viewed 75 times

-2

I have a precedent that returns value, but when it arrives in Executescalar() of c# it returns the error "Object reference not set to an instance of an object"

The trial is perfect

            private string IdentificaPat()
            {
                db.Configuration.AutoDetectChangesEnabled = false;
                db.Configuration.ValidateOnSaveEnabled = false;
                string retorno;
                string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {

                    using (SqlCommand cmd = new SqlCommand("Sp_InsertContratoGestores"))
                    {
                        cmd.CommandTimeout = 300;
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Connection = con;
                        con.Open();
                        retorno = cmd.ExecuteScalar().ToString();
                        con.Close();
                    }
                }
                if(retorno == "vazio")
                {
                    return "Vazio";
                }
                else
                {
                    return "Sem novos contratos";
                }

                db.Configuration.AutoDetectChangesEnabled = true;
                db.Configuration.ValidateOnSaveEnabled = true;
            }
  • 2

    probably his cmd.ExecuteScalar() is returning NULL and makes that mistake on account of ToString()

1 answer

0

I see you’re using EF6, so you can simplify this call to.:

db.Database.SqlQuery<string>("Sp_InsertContratoGestores");

Browser other questions tagged

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