Executing a stored procedure/function is easier in entity framework. The following steps explain how to call a stored procedure/function and return single or tabular values.

Step 1: Create an entity class which inherits “DbContext” class.

  1. public partial class MyDatabaseEntites: DbContext {
  2. public MyDatabaseEntites(): base("name=MyDatabaseEntites") {
  3. }
  4. public DbSet < Table1 > Table1DbSet {
  5. get;
  6. set;
  7. }
  8. public DbSet < Table2 > Table2DbSet {
  9. get;
  10. set;
  11. }............
  12. }
Step 2: The following is the structure of the database with table and stored procedure.

table
  1. CREATE PROCEDURE GetTable1Data
  2. AS
  3. SELECT * FROM Table1
  4. GO
Step 3: Create a class to store the returned tabular value.
  1. public class Table1Results
  2. {
  3. public int Column1 {get; set;}
  4. public string Column2 {get; set;}
  5. public string Column3 {get; set;}
  6. public string Column4 {get; set;}
  7. }
Step 4: Create an object for the entity above and method to call a function.
  1. public class RepositoryClass {
  2. private readonly DbContext myDatabaseReposityContext = null;
  3. public RepositoryClass() {
  4. myDatabaseReposityContext = new MyDatabaseEntites();
  5. }
  6. public List < Table1Results > GetTable1DataFromProc() {
  7. var query = "Exec GetTable1Data";
  8. object[] parameters = new object[] {};
  9. var response = myDatabaseReposityContext.Database.SqlQuery < Table1Results > (query, parameters).ToList();
  10. return response;
  11. }
  12. }
Step 5: Call the “RepositoryClass” class and “GetTable1DataFromProc” method.