is it possible to execute a stored procedure using EF, that select records from database from two or more tables using inner join and left outer join.
my point of vi
We are going to see how to execute the stored procedure in Entity Framework, in MVC we are going to see the how to add the EF.
Execute the following script in the database to create a stored procedure.
CREATE PROCEDURE FETCHEMPLOYEES AS
BEGIN
SELECT * FROM EMPTABLE
END
CREATE PROCEDURE FETCHEMPLOYEE(@ID INT) AS
BEGIN
SELECT * FROM EMPTABLE WHERE ID = @ID
END
public class EmpModel
{
EmployeeEntities empdb = new EmployeeEntities();
public List<EMPTABLE> GetEmployees()
{
return empdb.FETCHEMPLOYEES().ToList();
}
public EMPTABLE GetEmployee(int? id)
{
return empdb.FETCHEMPLOYEE(id).ToList().Single();
}
}
public class EmployeeController : Controller
{
Models.EmpModel mod = new Models.EmpModel();
public ActionResult Index()
{
List<EMPTABLE> result = mod.GetEmployees();
return View(result);
}
public ActionResult Details(int id)
{
EMPTABLE result = mod.GetEmployee(id);
return View(result);
}
}
For more step by step details, please refer following link: http://dotnetvisio.blogspot.in/2014/01/execute-stored-procedure-using-entity.html
You can call SqlQuery
from your Entity Framework data context.
context.Database.SqlQuery<YourType>("exec usp_StoredProcedure").ToList()
You would need a class to map the query results back, as an example:
public class YourType
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
You can also specify parameters to the query as shown below:
SqlParameter parameter1 = new SqlParameter("@Parameter1", "Value");
context.Database.SqlQuery<YourType>("exec usp_StoredProcedure @Parameter1", parameter1).ToList()
you can use ExecuteFunction
of ObjectContext
class:
public virtual ObjectResult<CustomClassForStoreReturnedData> NameOfStoredProcedure(Nullable<int> tableID)
{
var IDParameter = tableID.HasValue ?
new ObjectParameter("tableID", tableID) :
new ObjectParameter("tableID", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<CustomClassForStoreReturnedData>("NameOfStoredProcedureInSQLDatabase", IDParameter);
}
In you are using Entity Framework with MySQL:
In this example, my stored procedure is expecting one parameter, named myParam of type BIGINT
var myParam = new SqlParameter("@myParam", (MySqlDbType.Int64)).Value = 100;
var res = _context.Database.SqlQuery<MyEntity>($"call MyProcedureName({pyParam})");
Note that I am using C# String Interpolation to build my query string.