Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Stored Procedures with EntityFramework?

I have generated an EF4 Model from a MySQL database and I have included both StoredProcedures and Tables.

I know how to make regular instert/update/fetch/delete operations against the EF but I can't find my StoredProcedures.

This was what I was hoping for:

using (Entities context = new Entities()) {     context.MyStoreadProcedure(Parameters);  } 

Edit 1:

This is how it looked without EF:

sqlStr = "CALL updateGame(?,?,?,?,?,?,?)";  commandObj = new OdbcCommand(sqlStr, mainConnection); commandObj.Parameters.Add("@id,", OdbcType.Int).Value = inGame.id; commandObj.Parameters.Add("@name", OdbcType.VarChar, 255).Value = inGame.name; commandObj.Parameters.Add("@description", OdbcType.Text).Value = ""; //inGame.description; commandObj.Parameters.Add("@yearPublished", OdbcType.DateTime).Value = inGame.yearPublished; commandObj.Parameters.Add("@minPlayers", OdbcType.Int).Value = inGame.minPlayers; commandObj.Parameters.Add("@maxPlayers", OdbcType.Int).Value = inGame.maxPlayers; commandObj.Parameters.Add("@playingTime", OdbcType.VarChar, 127).Value = inGame.playingTime;      return Convert.ToInt32(executeScaler(commandObj)); 

PS. I can change EF version if needed

Edit 1:

CREATE DEFINER=`106228`@`%` PROCEDURE `updateGame`(     inId INT,     inName VARCHAR(255),     inDescription TEXT,     inYearPublished DATETIME,     inMinPlayers INT,     inMaxPlayers INT,     inPlayingTime VARCHAR(127) ) 
like image 972
Ivy Avatar asked Jan 10 '13 18:01

Ivy


People also ask

Does Entity Framework allow calling stored procedure?

Entity Framework has the ability to automatically build native commands for the database based on your LINQ-to-Entities or Entity SQL queries, as well as build the commands for inserting, updating, and deleting data. You may want to override these steps and use your own predefined stored procedures.


Video Answer


2 Answers

One way is to use the Database property off the DbContext:

SqlParameter param1 = new SqlParameter("@firstName", "Frank"); SqlParameter  param2 = new SqlParameter("@lastName", "Borland"); context.Database.ExecuteSqlCommand("sp_MyStoredProc @firstName, @lastName",                                param1, param2); 

EF5 definitely supports that.

like image 141
Quinton Bernhardt Avatar answered Sep 20 '22 21:09

Quinton Bernhardt


You have use the SqlQuery function and indicate the entity to mapping the result.

I send an example as to perform this:

var oficio= new SqlParameter {     ParameterName = "pOficio",     Value = "0001" };  using (var dc = new PCMContext()) {     return dc.Database              .SqlQuery<ProyectoReporte>("exec SP_GET_REPORTE @pOficio",                                         oficio)              .ToList(); } 
like image 45
user2997069 Avatar answered Sep 20 '22 21:09

user2997069