Stored Procedures With Entity Framework

A Stored Procedure is a group of transactional SQL statements. If you write the same query many times then we can write that query as a Stored Procedure and call it by its name.

Here we will learn about Stored Procedures in the Entity Framework with an example.

Step 1. First, create a table with the name “StudentStoredProcedure” Provide a column name for this table and insert some value into this.

StudentStoredProcedure

Step 2. Now create a Stored Procedure for inserting, updating, and deleting.

Create procedure InsertStudentInfo    
@Name nvarchar(50),    
@Gender nvarchar(50),    
@Branch nvarchar(50)    
as    
Begin    
Insert into StudentStoredProcedure values (@Name, @Gender,@Branch)    
End    
Go    
Create procedure UpdateStudentInfo    
@ID int,    
@Name nvarchar(50),    
@Gender nvarchar(50),    
@Branch nvarchar(50)    
as    
Begin    
Update StudentStoredProcedure Set Name = @Name, Gender = @Gender,    
Branch = @Branch    
where ID = @ID    
End    
Go    
Create procedure DeleteStudentInfo    
@ID int    
as    
Begin    
Delete from StudentStoredProcedure where ID = @ID    
End    
Go

Script

After writing this Stored Procedure script execute this and go to Programmability and expand the Stored Procedure. There you will see 3 Stored Procedures with the names “InsertStudentInfo”, “UpdateStudentInfo” and “DeleteStudentInfo”.

Stored Procedure

Step 3. Now create a new project and right-click on Solution Explorer and click on “add new item” select “ADO.Net Entity Data Model” and select "EF Designer from database". Then click on "Next".

EF Designer

Step 4. Here provide the connection and select your table and specify the app. config name as “SP_EntityFramework” and click on "Next".

EntityFramework

Step 5. Select the table name as StudentStoredProcedure. First, check that the Import selected Stored Procedures and functions into the entity model checkbox is selected or not, and then click Finish.

Finish

Step 6. After clicking on Finish, your Entity Data Model and Stored Procedure are created, but here you will not be able to see the Stored Procedure.

View Stored Procedure

Go to the Entity Model Designer surface and click on "Model Browser".

Now expand the Stored Procedures folder and you will see your Stored Procedures.

Model Browser

Step 7. Go to the Mapping Details, here you will see <Select Insert Function>, <Select Update Function>, <Select Delete Function>. Select one Stored Procedure for each one.

 Mapping Details

Step 8. Select InsertStudent info and like that, you can set it for all the functions.

Step 9. Now we need to validate it before executing to ensure it will give an error or not. Right-click on the designer surfer and click on Validate.

Step 10. Add a form and drag and drop a DataGridView from the toolbox.

Go to the smart tag of the DataGridView and add columns to it. When you click on the “add column” link you will see the following screen.

DataGridView

After adding the columns click OK. Then the DataGridView will be like the following.

Columns

Step 11. Again go to the smart tag of the DataGridView and select the DataSource as “BindingdataSource1”. On this screen, you will see a link as “Add project dataSource” and click on this.

DataSource

Click on Add Project to Data Source, then Database, and select Dataset. Now go to give a connection and provide a connection string name.

After clicking on Next you will see your tables. Select the table and Stored Procedure when you click on the OK button. When you run the application you will see data in the DataGridView.

The following code will be generated automatically.

private void Form1_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'for_entityDataSet.StudentStoredProcedure' table. You can use, or remove it, as needed.
    this.studentStoredProcedureTableAdapter.Fill(this.for_entityDataSet.StudentStoredProcedure);
}

Double-click on the DataGridView and write code for “Delete” and “insert”.

And provide the connection also.

builder.DataSource = "MUNESH";
builder.InitialCatalog = "ForEntity";
builder.IntegratedSecurity = true;
private void Form1_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'for_entityDataSet.StudentStoredProcedure' table. this.studentStoredProcedureTableAdapter.Fill(this.for_entityDataSet.StudentStoredProcedure);
}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    // Delete the row from database on gridview button click
    if (e.ColumnIndex == 1)
    {
        using(SqlConnection conn = new SqlConnection(builder.ToString()))
        {
            using(SqlCommand cmd = new SqlCommand("Ten Most Expensive Products", conn))
            {
                try
                {
                    conn.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    // _customQuery = new CustomQuery();
                    // SqlCommand sqlcmd= new SqlCommand();
                    SqlParameter parm = null;
                    cmd.CommandText = "DeleteStudentInfo";
                    cmd.Parameters.AddWithValue("@ID", Convert.ToInt64(dataGridView1.Rows[e.RowIndex].Cells[2].Value));
                    cmd.ExecuteNonQuery();
                    conn.Close();
                    Form1_Load(sender, e);
                }
                catch {}
            }
        }
    }

    // Insert into the row from database on gridview button click
    if (e.ColumnIndex == 0)
    {
        using(SqlConnection conn = new SqlConnection(builder.ToString()))
        {
            using(SqlCommand cmd = new SqlCommand("Ten Most Expensive Products", conn))
            {
                try
                {
                    conn.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    // _customQuery = new CustomQuery();
                    // SqlCommand sqlcmd= new SqlCommand();
                    SqlParameter parm = null;
                    cmd.CommandText = "InsertStudentInfo";
                    cmd.Parameters.AddWithValue("@Name", "MUNESH");
                    cmd.Parameters.AddWithValue("@GENDER", "MALE");
                    cmd.Parameters.AddWithValue("@BRANCH", "IT");
                    cmd.ExecuteNonQuery();
                    conn.Close();
                    Form1_Load(sender, e);
                }
                catch {}
            }
        }
    }
}

Step 12. Now run your application, and you will get the following output.

Output

You can visit my blog.


Recommended Free Ebook
Similar Articles