Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute stored procedure using entity framework [duplicate]

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 view is to avoid the method of doing joins in EF or LINQ, which i have many issues with it.

so if i create that procedure, can i call it with parameters from user input, can assign the result to .ToList() method and then add the result to asp:repeater .DataSource.

I know it may be a strange question, but i want to do this for many reasons first, to use EF because i feel more comfortable. second, to get rid of using joins in EF. third, i read somewhere that using stored procedure will enhance query performance, when used to call a query frequently.

if any one could help me to answer these questions with an example i would be appreciate.

like image 218
Fares Ayyad Avatar asked Aug 21 '16 09:08

Fares Ayyad


1 Answers

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()
like image 117
Darren Avatar answered Nov 10 '22 18:11

Darren