Sunday 31 January 2016

How to call Stored Procedure in Entity Framework

 Entity  frame work providing the option of adding, updating or deleting the records. It is also giving the way of calling the store procedure in entity Framework to Insert, Update and Delete the options.
Entity framework will create User defined function for store procedures.
 Let’s see how we can add call the store procedure in entity frame work.
1.              Creation of store procedure in database.



2.              Create an entity frame work;


3.              Now you can see the list of tables and Store procedures in the wizard window. Like;



4.              Now its generated the class for the store procedure that you have added like below;


It has generated the code like:
  public virtual ObjectResult<GetEmployeeDetailsnyID_Result> GetEmployeeDetailsnyID(Nullable<int> id)
        {
            var idParameter = id.HasValue ?
                new ObjectParameter("Id", id) :
                new ObjectParameter("Id", typeof(int));
   
            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<GetEmployeeDetailsnyID_Result>("GetEmployeeDetailsnyID", idParameter);
        }

But it won’t generate anything in designer.

5.              Now the time to call that method and see the output.

class Program
    {
        static void Main(string[] args)
        {
            using (var context = new CompanyDetailsEntities())
            {
                var emps = context.GetEmployeeDetailsnyID(1);

                foreach (var e in emps)
                    Console.WriteLine(e.Name);
            }
        }
    }

Output generated as,

 Or
 You can call the store procedure like below;

  using (var context = new CompanyDetailsEntities())
            {
                var emps = context.Employees.SqlQuery("exec GetEmployeeDetailsnyID @Id =" + 1).ToList();

                foreach (var e in emps)
                    Console.WriteLine(e.Name);
            }




No comments:

Post a Comment