25 September 2012

Calling an stored procedure using ADO.NET Entity Model (Entity Framework LINQ to SQL)

Create new asp.net website in your solution. Now add new project as class library named as Business Layer. Add a new project again and name it DAL.
Add the reference of BusinessLayer to the asp.net website project. Similarly add the reference of DAL project to BusinessLayer. This all we are doing as we are trying to create a layered architecture for the sample application.
Now right click on DAL project and add new item -> ADO.NET Entity Model click ok.
Now it’ll ask you to configure your Model from the database. Here I’m skipping this step assuming that you may know how to configure the model using the wizard.

After configuration your model will be added and opened and will show all your tables you have select from the wizard.

1.Now create an storedProcedure in your database.
2. Come back to you solution and open the sampleModel.edmx from the DAL project and right click.
3. Click on “Update the model from database” it’ll open the same wizard that was appeared while you were adding the Model. But this time it’ll only show the newly added item in the database.
4. Expand the stored procedure item and select your stored procedure from the list.

Now click finish and save the Model.
5. Go to the visual studio menu and  select View->Other Windows -> Entity Data Model Browser

6. Now open the Model Browser and expand EntityContainer and right click on “Fucntion Imports” and click “Add Function Import…”.
7. Name the function “GetAllEmployees” and select the available storedprocedure in the model from the dropdown list GetAllEmployees. Now select the return type so you are going to show the emplyee details so the return type would be the Entity: Employee

8. Click on and save the model.
Now write the code in your business layer to get the returned data from the Stored Prodcedure.
using DAL;
namespace BusinessLayer
{
    public class Employees
    {
        public static List<Employee> GetAllEmployeesInfo()
        {
            btnetEntities data = new btnetEntities();
            var EmpCol = data.GetAllEmployees();
            var EmpItems = from e in EmpCol
                           select new Employee
                           {
                               Eid = e.employee_id,
                               Name = e.employee_name,
                               EMail = e.email

                           };
            List<Employee> ls = new List<Employee>(EmpItems.ToList());
            return ls;
        }
    }
}

In your aspx page bind the grid:
using BusinessLayer;

namespace EFLinqToSqlDemo
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            GridView1.DataSource = Employees.GetAllEmployeesInfo();
            GridView1.DataBind();
        }
    }
}

And you are done.:))



Here’s the output.