Zohaib
Zohaib

Reputation: 649

Calling stored procedure from Entity Framework in C#

This is my output looks like...

and this is my backend

Beta_DatabaseEntities db = new Beta_DatabaseEntities();
table2 tb = new table2();

int ID;
string Name;
int Salary;

public void Entry()
{
        ID = Convert.ToInt16(id.Text);
        Name = name.Text;
        Salary = Convert.ToInt32(salary.Text);
}

private void insert_Click(object sender, EventArgs e)
{
        Entry();
        tb.Id = ID;
        tb.Name = Name;
        tb.Salary = Salary;
        db.table1.Add(tb);
        db.SaveChanges();
        db.Database.ExecuteSqlCommand("GradeEntry "+)
}

My stored procedure:

create procedure GradeEntry
     (@ID int, @name nvarchar(50), @salary int)
As
Begin
    if(@salary >= 2500)
    Begin
        insert into Table2 values(@ID, @name, 'A+', @salary)
    End
    else if(@salary >= 1000)
    Begin
        insert into Table2 values(@ID, @name, 'A', @salary)
    End
    else if(@salary >= 500)
    Begin
        insert into Table2 values(@ID, @name, 'B', @salary)
    End
    else
    Begin
        insert into Table2 values(@ID, @name, 'Interni', @salary)
    End
End

I am working with Entity Framework but can't figure out how to call the stored procedure working in C#. I am using Visual Studio 2013

I just want to call the stored procedure from C# using Entity Framework.

Upvotes: 2

Views: 7475

Answers (1)

Alex
Alex

Reputation: 38499

You are almost there with your ExecuteSqlCommand

You just need to add EXEC, then pass in the parameters:

db.Database.ExecuteSqlCommand("EXEC GradeEntry @ID, @name, @salary",
    new SqlParameter("@ID", ID),
    new SqlParameter("@name", Name),
    new SqlParameter("@salary", Salary),
)

ExecuteSqlCommand takes an array of object, as parameters.

Upvotes: 2

Related Questions