Execute stored procedure using entity framework

c# entity-framework linq mysql sql-server

Question

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.

1
7
8/21/2016 9:58:56 AM

Accepted Answer

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()
20
8/21/2016 10:04:18 AM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow