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);
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With