Vahid Beyranvand
Vahid Beyranvand

Reputation: 67

How to call stored procedure by Web API

Is it possible to use Web API without Entity framework and calling stored procedure from Web API controllers?

Upvotes: 1

Views: 6369

Answers (1)

BNK
BNK

Reputation: 24114

It's possible, as the following sample:

        public async Task<IHttpActionResult> Get()
        {
            DataTable dt = new DataTable();            

            using (SqlConnection sqlConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
            {
                await sqlConnection.OpenAsync();

                using (SqlCommand cmd = new SqlCommand("sp_GetData", sqlConnection))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;

                    using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
                    {
                        dt.Load(reader);                        
                    }                    
                }
            }

            if ((dt == null) || (dt.Rows.Count == 0))
            {
                return NotFound();
            }

            return Ok(dt);
        }

Hope it helps!

Upvotes: 4

Related Questions