Search code examples
entity-frameworksql-server-2008stored-procedurescode-firstentity-framework-6

How to execute a stored procedure without returning results in Entity Framework 6?


I have a stored procedure like this:

CREATE PROCEDURE InsertTest(@p1 NVARCHAR(50) , @p2 INT)
AS 
BEGIN 
   INSERT INTO dbo.Test(Name, Code)
   VALUES ( N'', 0)
END

or other

I try with this code:

context.Database.SqlQuery<int>("InsertTest @p1 , @p2", "a",1);

But this leads to error.

How can I run it using DbContext ?


Solution

  • Do this.

    context.Database.ExecuteSqlCommand(
       "InsertTest @p1 , @p2", 
       new SqlParameter("@p1", "a"),
       new SqlParameter("@p2", 1));
    

    or

    context.Database.SqlQuery<object>(
       "exec InsertTest @p1 , @p2", 
       new SqlParameter("@p1", "a"),
       new SqlParameter("@p2", 1)).FirstOrDefault();