Calling Stored procedures with Datacontext in MVC


We can call stored procedures in the entity data model using below code we can pass parameters

and get the results



using (EntityConnection conn = new EntityConnection("name=EntitiesName"))
                        {
                            conn.Open();
                            // Create an EntityCommand.
                            using (EntityCommand cmd = conn.CreateCommand())
                            {
                                cmd.CommandText = "EntitiesName.StoredProcedureName";
                                cmd.CommandType = CommandType.StoredProcedure;
                                EntityParameter param = new EntityParameter();
                                param.Value = Id;
                                param.ParameterName = "Name";
                                cmd.Parameters.Add(param);
                                EntityParameter param1 = new EntityParameter();
                                param1.Value = Id2;
                                param1.ParameterName = "Name2";
                                cmd.Parameters.Add(param1);

                                // Execute the command.
                                using (EntityDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
                                {
                                    // Read the results returned by the stored procedure.
                                    if (reader.HasRows == true)
                                    {
                                        while (reader.Read())
                                        {
                                            Model objModel = new Model();

                                            objModel.Id = (Int32)reader["Id"];
                                            objModel.Name = reader["Name"].ToString();

                                            ModelList.Add(objModel);
                                        }
                                    }
                                }
                            }
                            conn.Close();
                        }


0 comments:

Post a Comment

Vikram Chandra Theme by BloggerThemes & NewWPThemes Sponsored by iBlogtoBlog