Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing stored procedures from a DbContext

I have two simple stored procedures in SqlServer:

  • SetData(@id int, @data varchar(10))
  • GetData(@id int).

GetData currently returns a single-row, single-column result set, but I could change it to be a proper function if needed.

What would be the best way to execute these from a DbContext instance?

If possible, I'd like to avoid having to do my own connection state management and/or exposing EF-specific types. I started by retrieving the ObjectContext and looking at the Execute* functions, but the documentation is pretty bad and lacking examples involving stored procedures.

Ideally, I'd like to be able to do this:

myContext.ExecuteNonQuery("SetData", id, data);
var data = myContext.ExecuteScalar<string>("GetData", id);
like image 495
Diego Mijelshon Avatar asked Jun 08 '11 16:06

Diego Mijelshon


People also ask

Can Entity Framework call stored procedure?

There are many ways to call Stored Procedures from Entity Framework. The prerequisite for running these examples are the following sample tables with test data and a Stored Procedure. The following script help to generate the table with test data and a Stored Procedure.

Can we call stored procedure in Entity Framework Core?

The support for stored procedure in EF Core is similar to the earlier versions of EF Code first. You need to create your DbContext class by inherting the DbContext class from EF. The stored procedures are executing using the DbContext. First step is to write a method that create a DbCommand from the DbContext.

How do I run a stored procedure in EF Core 5?

From this object, you can create a command object using the CreateCommand() method. Fill in the CommandText property of the command object with the SQL statement you created with the call to the stored procedure. Open the connection on the database object and you're now ready to call the stored procedure.


1 Answers

DbContext offers these functions. Use:

IEumerable<...> result = myContext.Database.SqlQuery<...>(...)

to execute retrieval stored procedure and

int result = myContext.Database.ExecuteSqlCommand(...)

to execute data modification stored procedure.

like image 114
Ladislav Mrnka Avatar answered Sep 21 '22 05:09

Ladislav Mrnka