Tuesday, May 14, 2013

How to call a stored procedure through MVC 4 and Entity Framework 5.0


Create database


  •         Just we have to create a simple database named as student
  •         We also create simple table named as student
  •        Write a simple stored procedure

USE [Student ]
GO
/****** Object:  StoredProcedure [dbo].[GetStudents]    Script Date: 05/14/2013 12:56:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[GetStudents]

As
Begin
   select * from dbo.StudentDetails
End

Add Edmx

As we know how to add edmx file. In the second step of adding edmx file (choose your database objects and settings). Let we choose the stored procedure and functions checkbox and expand the checkbox and select which stored procedure you want. Then proceed the other steps finally we get an edmx files and related context classes.



As we know about EDM (Entity Data Model) However, just remember the Storage model, It is your database design model which includes tables, views, stored procedures and their relationships and keys.The Storage model stored procedure configuration like below 

public partial class GetStudents_Result
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Class { get; set; }
    }

  public virtual ObjectResult<GetStudents_Result> GetStudents()
        {
            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<GetStudents_Result>("GetStudents");
        }


Then we access the stored procedure in controller. So we create a object for our entity class 
            
            StudentEntities entity = new StudentEntities();

            var sd = entity.GetStudents().ToList();
            return View(sd);

Conclusion 

If any one have any doubts and corrections plese comment me  Thanks
Abiruban@ Niventh





4 comments:

  1. very usefull notes and we need more information on this topic please post updated data . thanks for your post.
    Dot net online tutorials


    ReplyDelete
  2. for insertstoreprocedure code in controller

    ReplyDelete
  3. Thanku for sharing this nice posts..
    In this course, covers all processes and components of the SAP solutions for Governance, Risk, and Compliance. You will learn how you can guarantee the compliance of business processes and IT systems with Process Control
    SAP GRC training in hyderabad


    ReplyDelete