Consuming The Entity Framework Model in ASP.NET Web Application

How Can we Consume EF Model in Web Application ?


In the previous article, we have seen how to create our first Entity Framework model in VS 2013. Today in this article we will be consuming this model in a web application. The main goal of this article in to consume the model and to bind a grid view in an aspx page. So our out put will look something like this.
Grid view with data coming from EF Model
This grid is having the data we have in the customer table of AdventureWorks database. I will be taking you through how to use this entity framework model in your web application. Let's start now.




Consuming an EF Model in ASP.NET Web Application


First you need to create a project for the Entity Framework Model. Create an Empty Project in your Visual Studio. Then add a console application to it. Then follow my previous article to create your Model first. Here is the link Introduction to Entity Framework in ASP.NET (Creating an EF Model in Visual Studio 2013).




Once you are done then here we go. No add another empty website to that solution. and add a new aspx page named ShowGrid.aspx page.
New project to consume EF Model
Now we need to add a reference of the class library we have created for our AW Model in previous article. Go and add a reference.
Add reference




Now select the Project table from the options while adding a new reference. There you will find the library for AWModel. Now add it.
Select reference.
Now all the set up for our project is done. Lets see how to use EF model to get data from database.
Here is the aspx that contains the grid view. (There is few more lines of code for making the page a bit beautiful. You can ignore them, but I can not as I love designing the most.)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ShowGrid.aspx.cs" Inherits="WebApplicationToConsumeModel.ShowGrid" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>User List - Demo Application on EF Model</title>
    <link href="css/bootstrap.css" rel="stylesheet" />
    <script src="js/jquery-1.8.2.min.js"></script>
    <script src="js/bootstrap.js"></script>
    <style>
        #lblError {
            color: red;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <div class="panel panel-default" style="margin-top: 10px;">
                        <div class="panel-heading">
                            <h3 class="panel-title">User List - Demo Application on EF Model</h3>
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-md-10">
                                    <asp:Label CssClass="error" runat="server" ID="lblError"></asp:Label>
                                </div>
                                <div class="col-md-2 col-md-offset-10">
                                    <asp:LinkButton runat="server" ID="btnRefreshData" CssClass="btn btn-primary btn-sm"><span class='glyphicon glyphicon-refresh'></span></asp:LinkButton>
                                </div>
                            </div>
                            <br />
                            <br />
                            <div class="row">
                                <div class="col-md-12 ">
                                    <asp:GridView runat="server" ID="grdDemo" AutoGenerateColumns="True" CssClass="table table-bordered table-hover table-striped table-responsive">
                                    </asp:GridView>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </form>
</body>
</html>
Now lets move into the code behind, where we need to fetch the data from EF Model and to bind that to the grid view. So for that thing we have to use LINQ.

Firstly create a custom class for person, which will have some 3 fields named customerID, Name, AccountNo. Find how it looks like.
/// <summary>
    /// Create a class named Person to hold data
    /// </summary>
    public class person
    {
        public int customerID { get; set; }
        public string Name { get; set; }
        public string AccountNo { get; set; }
    }
Now lets write the LINQ which will fetch the data from EF Model. First create an object of the AWModel class. Once you declare the object this object will let us to access the table object directly. See the below image how the object is predicting all the table objects to me.
Table Objets
Here is the code for the method. Check it out.
/// <summary>
        /// This method is responsible for binding the grid.
        /// </summary>
        private void PopulateCustomerGrid()
        {
            var customerObject = new AWModel.AWEntities();

            // var query = (from c in customerObject.Customers select c).Take(10);
            var query = (from c in customerObject.Customers select new person() { customerID = c.CustomerID, Name = c.Person.FirstName, AccountNo = c.AccountNumber }).ToList().Take(10);
            List<person> customers = query.ToList();

            // Convert the list to data table
            DataTable dt = ToDataTable(customers);

            // Bind the data table
            grdDemo.DataSource = dt;
            grdDemo.DataBind();
        }
If you look into the LINQ you can find out that I am selecting only 10 records from the Customers Table, and Take(10)  is responsible for that. The LINQ query returns a list and we need to hod that in a class object. For this we have created the Person class above.




Let's take a list of Person class and hold the return value of the LINQ querry.

You can see  there is a method called ToDataTable(customers) method. This method is responsible for converting the list into data table. This method takes the list only and returns you a custom Data Table. Find it here.
        /// <summary>
        /// Convert a list into a custom data table
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <returns></returns>
        public DataTable ToDataTable<T>(List<T> items)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);

            //Get all the properties
            PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo prop in Props)
            {
                //Setting column names as Property names
                dataTable.Columns.Add(prop.Name);
            }

            foreach (T item in items)
            {
                var values = new object[Props.Length];

                for (int i = 0; i < Props.Length; i++)
                {
                    //inserting property values to datatable rows
                    values[i] = Props[i].GetValue(item, null);
                }
                dataTable.Rows.Add(values);
            }

            //put a breakpoint here and check datatable
            return dataTable;

        }
Find the whole code behind here. ShowGrid.aspx.cs page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Reflection;

namespace WebApplicationToConsumeModel
{
    /// <summary>
    /// Create a class named Person to hold data
    /// </summary>
    public class person
    {
        public int customerID { get; set; }
        public string Name { get; set; }
        public string AccountNo { get; set; }
    }

    public partial class ShowGrid : System.Web.UI.Page
    {
        /// <summary>
        /// Bind the grid.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            PopulateCustomerGrid();
        }

        /// <summary>
        /// This method is responsible for binding the grid.
        /// </summary>
        private void PopulateCustomerGrid()
        {
            var customerObject = new AWModel.AWEntities();

            // var query = (from c in customerObject.Customers select c).Take(10);
            var query = (from c in customerObject.Customers select new person() { customerID = c.CustomerID, Name = c.Person.FirstName, AccountNo = c.AccountNumber }).ToList().Take(10);
            List<person> customers = query.ToList();

            // Convert the list to data table
            DataTable dt = ToDataTable(customers);

            // Bind the data table
            grdDemo.DataSource = dt;
            grdDemo.DataBind();
        }

        /// <summary>
        /// Convert a list into a custom data table
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <returns></returns>
        public DataTable ToDataTable<T>(List<T> items)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);

            //Get all the properties
            PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo prop in Props)
            {
                //Setting column names as Property names
                dataTable.Columns.Add(prop.Name);
            }

            foreach (T item in items)
            {
                var values = new object[Props.Length];

                for (int i = 0; i < Props.Length; i++)
                {
                    //inserting property values to datatable rows
                    values[i] = Props[i].GetValue(item, null);
                }
                dataTable.Rows.Add(values);
            }

            //put a breakpoint here and check datatable
            return dataTable;

        }
    }
}
I hope you enjoy this article on how to consume the EF Model in a web application. If you like it then please support us by sharing it.




Happy Coding...

No comments:

Post a Comment