Tech Junkie Blog: Entity Framework (Database First) Part 3: Using the Entity Framework Objects In ASP.NET Project

Thursday, February 12, 2015

Entity Framework (Database First) Part 3: Using the Entity Framework Objects In ASP.NET Project

This is part three of our series on Entity Framework. In the last blog we went over how to create an Entity Framework model with the Northwind database. Now we are going to use that model in our ASP.NET by binding the Entity objects that have created to a GridView in our "Northwind" ASP.NET project. Usually we would put the Entity Framework model in a class library project and use it as our data access layer, but for simplicity I've decided to put in the same project as the ASP.NET pages.

Below are the directions on how to use the Entity objects in our web pages.

1. Create "Default.aspx" page in the "Northwind" web project.





2. Add a GridView control to the page.



3. In the "Default.aspx.cs" file add the following using statement
using Northwind.Models;
Northwind.Models is the namespace of models that we just created.

4. Then in the Page_Load method write the following code.
        protected void Page_Load(object sender, EventArgs e)
        {
            using(NorthwindEntities nwctx = new NorthwindEntities())
            {
                var query = from prod in nwctx.Products
                            select prod;

                GridView1.DataSource = query.ToList();
                GridView1.DataBind();
            }
        }

The code above creates a new instance of the NorthwindEntities database context. We use create it inside the "using" statement because the advantage of using the "using" statement is that the object will be automatically disposed of when it's not needed. It's good to use the "using" statement with resources related objects.

After we assign the new NorthwindEntities object to the variable "nwctx" we use LINQ to query select all the "Products" Entity objects in the "Products" DbSet. If you look inside the code file "NorthwindModel.Context.cs" file you will see that when you create the "NorthwindEntities" object you are creating an instance of this class, and it will give you to the DbSet of all the objects in the model. DbSet gives you a collection of all the entity objects so that you can work with it. Below is the code inside the "NorthwindModel.Context.cs" file

namespace Northwind.Models
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    
    public partial class NorthwindEntities : DbContext
    {
        public NorthwindEntities()
            : base("name=NorthwindEntities")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet Categories { get; set; }
        public virtual DbSet CustomerDemographics { get; set; }
        public virtual DbSet Customers { get; set; }
        public virtual DbSet Employees { get; set; }
        public virtual DbSet Order_Details { get; set; }
        public virtual DbSet Orders { get; set; }
        public virtual DbSet Products { get; set; }
        public virtual DbSet Regions { get; set; }
        public virtual DbSet Shippers { get; set; }
        public virtual DbSet Suppliers { get; set; }
        public virtual DbSet Territories { get; set; }
    }
}


5. Once we get the list of "Products" from our LINQ query we bind our result to the GridView on our "Default.aspx" page. It's important that you call the .ToList(); method on the LINQ query, or the "Default.aspx" page will throw an error. What the .ToList() method does is that it converts the LINQ query to return a list of objects. So you are actually binding the GridView control to a list of objects. After you have define the datasource for the GridView you just call the DataBind() method to bind the list of "Products" to the GridView.

                GridView1.DataSource = query.ToList();
                GridView1.DataBind();


6. If you click Ctrl+F5 to run the Default.apsx page you will see that GridView has been populated with the records in the Northwind database.




So you just got yourself a data access layer with the Entity Framework without much effort on your part. Because Entity Framework maps your database to objects it works well with other ASP.NET and Microsoft technologies such as MVC and WCF, because you are just dealing with objects not the underlying database. You don't have to worry about creating the database the connections or none of the complexity, it's all been encapsulated with the DbContext class.

Blogs in the Entity Framework Series:

  1. Installing Entity Framework 6.1.1 With NuGet
  2. Creating Entity Model From an Existing Database Entity Framework 6.1.1
  3. Using the Entity Framework Objects In ASP.NET Project
  4. Entity Framework (Database First) Part 4: Using the LINQ and Projection To SELECT Columns From Entities


No comments:

Post a Comment