Tuesday, July 1, 2008

How to read data using stored procedure in LINQ


  • Step 1 : Create DataContext classes
  1. Create the new project named 'KannanBlogDemo' from Visual studio 2008 under your favirote folder.
  2. Right click the 'KannanBlogDemo' project and select add-->item add.
  3. Select 'LINQ to SQL classes' from Add new item window.
  4. Open Server Explorer and connect your database to be test. For an example, I have created 'KannanBlog' as database with three tables, namely PatientInformation, Facility and PrimaryLanguages. See the below snap for more information.
  5. Once database connected well, then we can see the tables, stored procedures, view and so on which blongs to the database. See the below snap for more information.
  6. Now, drag and drop the tables and stored procedures to be test into the Object Relation Designer. See the below snap for more information.
  7. Once we completed our drag and drops, the system will automatically create DataContext classes for each and every tables along with database name for further references as .dbml files.
  8. Now 'KannanBlogDemoDataContext' is ready to use.
  • Step 2 : Select the record through stored procedure.
  1. Open default.aspx file and add gridview control.
  2. In default.aspx.cs files, page load event add the data fetching coding given below.
    protected void Page_Load(object sender, EventArgs e)
    {
    var db= new KannanBlogDemoDataContext();
    var patient = db.SelectAllPatinetInformation();
    GridView1.DataSource = patient;
    GridView1.DataBind();
    }


  3. Here, 'SelectAllPatientInformation' is the name of the store procedure, which fetch all the patient informations from the database.
  4. Run the application and see the result as below.

    Happy Programming!!!