After I wrote several articles on this site, I found out it seemed almost for every article, I needed to set up a sample application associated with an entity framework if accessing the database. And, every time, I needed to rewrite the setup process from scratch in order for a new reader to follow along easily. Even for introducing a very simple concept, such as Caching, I needed to spend 80% of the time setting up the sample app, and only 20% on introducing the Caching concept itself.
Therefore, I think it is better to write a basic model such as entity framework sample for various approaches, and then I can reuse them when needed. I made a list of the series of articles below, I will write them one by one, while the Entity framework overview and concept will be covered in the article (0):
- Entity Framework (0), Overview
- Entity Framework (1), with .Net MVC, Code-First
- Entity Framework (2), with .Net MVC, Database-First
- Entity Framework (3), with .Net MVC, Model-First
- Entity Framework (4), with .Net Core MVC, Code-First
- Entity Framework (5), with .Net Core MVC, Database-First
- Entity Framework (6), with .Net Core MVC, Model-First
- Entity Framework (7), with .Net WPF, Database-First
- Entity Framework (8), with .NET Core Web API, Stored Procedure
- Entity Framework (9), with .NET Core Web API, Stored Procedure Implementation
- Entity Framework (10), with .Net WebForms, Database-First --- this article
- Entity Framework (11), with .Net Core Razor Pages Code-First
- Entity Framework (12), with New .Net Core MVC Code-First
Note
The entity framework is usually used associated with ASP.NET MVC module,with less chance used with WebForms, because when Entity Framework and MVC module came to the market almost at the same time when most of new projects moved to MVC module. However, when the Entity Framework is used with WebFormd, the pattern is the same as it is used with MVC. So, this article will follow Entity Framework (2), with .Net MVC, Database-First. we just emphasize the major difference here.
Introduction
This article is about Entity Framework with .Net WebForms, Database-First approach. We will make a sample app step by step,
- Step 1: Create an ASP.NET WebForms application
- Step 2: Reverse Engineer Model
- Step 2-1, Alternative Approach: Code First
- Step 3: Data Binding
At the end, we will have a .Net WebFomrs app that can consume a database directly through entity framework.
Step 1 - Create an ASP.NET WebForms app
We use the current version of Visual Studio 2019 16.9.3 and .NET Framework 4.8 to build the app:
- Start Visual Studio and select Create a new project.
- In the Create a new project dialog, select ASP.NET Web Application (.NET Framework) > Next.
- In the Configure your new project dialog, enter WebForms_DatabaseFirst for Project name > Create.
- In the Create a new ASP.NET Web Application dialog, select Web Fomrs > Creat
Build and run the app, you will see the following image shows the app (the same as MVC)
Step 2, Reverse Engineer Model
For this step, whatever WPF or Web app (MVC or Web API or Web Forms), they are all the exactly same. We will skip the procedure and use the result at Step 2, from Article Entity Framework (2), with .Net MVC, Database-First,
Once the reverse engineer process completes the new model is added to the project and opened up for viewing in the Entity Framework Designer:
The created entity class, the entity context and the connection string will be exactly the same as ones in the MVC module, where the Store class is like this:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebForms_DatabaseFirst
{
using System;
using System.Collections.Generic;
public partial class store
{
public string stor_id { get; set; }
public string stor_name { get; set; }
public string stor_address { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
}
}
The Data Context will be in pubsEntities class:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebForms_DatabaseFirst
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class pubsEntities : DbContext
{
public pubsEntities()
: base("name=pubsEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<store> stores { get; set; }
}
}
and the connection details for the database will be inserted into web.config file,
<connectionStrings>
<add name="pubsEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=pubs;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
Step 2-1, Alternative Approach: Code First
In fact, the Code First approach for .NET Framework is quite simple, just using the entity class and context as created above, even the connection string is not necessary, as simple as these,
Entity class
namespace WebForms_DatabaseFirst
{
public partial class store
{
public string stor_id { get; set; }
public string stor_name { get; set; }
public string stor_address { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
}
}
Context class
namespace WebForms_DatabaseFirst
{
using System.Data.Entity;
public partial class pubsEntities : DbContext
{
public virtual DbSet<store> stores { get; set; }
}
}
build the app, we have the database created automatically. See details from Article Entity Framework (1), with .Net MVC, Code-First,
Step 3 - Data Binding: Build the Grid, and Run the app
From both and either the Database First approach or Code First approach above, we got here for the next step: Data Binding, which is something of WebForms different from MVC or Web API module where we can use Scaffolder tool to build the CRUD (controller) associated with entity framework automatically.
Because this will be a normal Web Forms development, could be simple and coul be complex, we will make a sample here to demo how to hook the entiry with GridView.
Step 1:
Add a GridView control:
into a page (drag and drop):
The code in Default.aspx are
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebForms_DatabaseFirst._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS, and JavaScript.</p>
<p><a href="http://www.asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</asp:Content>
Step 2:
Data binding, the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebForms_DatabaseFirst
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Create an Entity Context instance
pubsEntities _pubsEntities = new pubsEntities();
// Fill the DataGrid View by the Entity
GridView1.DataSource = _pubsEntities.stores.ToList();
// Binding
GridView1.DataBind();
}
}
}
Output:
Summary
The .NET WebForms for Database-First approach is the exactly same for the entity framework building up process, but without Scaffolder to help automatically bind to Controls. Therefore, we will no discuss more details for further data binding issues. For more details, we can see the references below.
Reference