Create the Data Access Layer
by Erik Reitan
Download Wingtip Toys Sample Project (C#) or Download E-book (PDF)
This tutorial series will teach you the basics of building an ASP.NET Web Forms application using ASP.NET 4.5 and Microsoft Visual Studio Express 2013 for Web. A Visual Studio 2013 project with C# source code is available to accompany this tutorial series.
This tutorial describes how to create, access, and review data from a database using ASP.NET Web Forms and Entity Framework Code First. This tutorial builds on the previous tutorial “Create the Project” and is part of the Wingtip Toy Store tutorial series. When you’ve completed this tutorial, you will have built a group of data-access classes that are in the Models folder of the project.
What you’ll learn:
- How to create the data models.
- How to initialize and seed the database.
- How to update and configure the application to support the database.
These are the features introduced in the tutorial:
- Entity Framework Code First
- LocalDB
- Data Annotations
Creating the Data Models
Entity Framework is an object-relational mapping (ORM) framework. It lets you work with relational data as objects, eliminating most of the data-access code that you’d usually need to write. Using Entity Framework, you can issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. LINQ provides patterns for querying and updating data. Using Entity Framework allows you to focus on creating the rest of your application, rather than focusing on the data access fundamentals. Later in this tutorial series, we’ll show you how to use the data to populate navigation and product queries.
Entity Framework supports a development paradigm called Code First. Code First lets you define your data models using classes. A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events. You can map classes to an existing database or use them to generate a database. In this tutorial, you’ll create the data models by writing data model classes. Then, you’ll let Entity Framework create the database on the fly from these new classes.
You will begin by creating the entity classes that define the data models for the Web Forms application. Then you will create a context class that manages the entity classes and provides data access to the database. You will also create an initializer class that you will use to populate the database.
Entity Framework and References
By default, Entity Framework is included when you create a new ASP.NET Web Application using the Web Forms template. Entity Framework can be installed, uninstalled, and updated as a NuGet package.
This NuGet package includes the following runtime assemblies within your project:
- EntityFramework.dll – All the common runtime code used by Entity Framework
- EntityFramework.SqlServer.dll – The Microsoft SQL Server provider for Entity Framework
Entity Classes
The classes you create to define the schema of the data are called entity classes. If you’re new to database design, think of the entity classes as table definitions of a database. Each property in the class specifies a column in the table of the database. These classes provide a lightweight, object-relational interface between object-oriented code and the relational table structure of the database.
In this tutorial, you’ll start out by adding simple entity classes representing the schemas for products and categories. The products class will contain definitions for each product. The name of each of the members of the product class will be ProductID
, ProductName
, Description
, ImagePath
, UnitPrice
, CategoryID
, and Category
. The category class will contain definitions for each category that a product can belong to, such as Car, Boat, or Plane. The name of each of the members of the category class will be CategoryID
, CategoryName
, Description
, and Products
. Each product will belong to one of the categories. These entity classes will be added to the project’s existing Models folder.
In Solution Explorer, right-click the Models folder and then select Add -> New Item.
The Add New Item dialog box is displayed. 2. Under Visual C# from the Installed pane on the left, select Code.
![Create the Data Access Layer - New Item Menu](create_the_data_access_layer/_static/image2.png)
- Select Class from the middle pane and name this new class Product.cs.
- Click Add.
The new class file is displayed in the editor. Replace the default code with the following code:
[!code-csharpMain]1: using System.ComponentModel.DataAnnotations;
2:
3: namespace WingtipToys.Models
4: {
5: public class Product
6: {
7: [ScaffoldColumn(false)]
8: public int ProductID { get; set; }
9:
10: [Required, StringLength(100), Display(Name = "Name")]
11: public string ProductName { get; set; }
12:
13: [Required, StringLength(10000), Display(Name = "Product Description"), DataType(DataType.MultilineText)]
14: public string Description { get; set; }
15:
16: public string ImagePath { get; set; }
17:
18: [Display(Name = "Price")]
19: public double? UnitPrice { get; set; }
20:
21: public int? CategoryID { get; set; }
22:
23: public virtual Category Category { get; set; }
24: }
25: }
Create another class by repeating steps 1 through 4, however, name the new class Category.cs and replace the default code with the following code:
[!code-csharpMain]
1: using System.Collections.Generic;
2: using System.ComponentModel.DataAnnotations;
3:
4: namespace WingtipToys.Models
5: {
6: public class Category
7: {
8: [ScaffoldColumn(false)]
9: public int CategoryID { get; set; }
10:
11: [Required, StringLength(100), Display(Name = "Name")]
12: public string CategoryName { get; set; }
13:
14: [Display(Name = "Product Description")]
15: public string Description { get; set; }
16:
17: public virtual ICollection<Product> Products { get; set; }
18: }
19: }
As previously mentioned, the Category
class represents the type of product that the application is designed to sell (such as “Cars”, “Boats”, “Rockets”, and so on), and the Product
class represents the individual products (toys) in the database. Each instance of a Product
object will correspond to a row within a relational database table, and each property of the Product class will map to a column in the relational database table. Later in this tutorial, you’ll review the product data contained in the database.
Data Annotations
You may have noticed that certain members of the classes have attributes specifying details about the member, such as [ScaffoldColumn(false)]
. These are data annotations. The data annotation attributes can describe how to validate user input for that member, to specify formatting for it, and to specify how it is modeled when the database is created.
Context Class
To start using the classes for data access, you must define a context class. As mentioned previously, the context class manages the entity classes (such as the Product
class and the Category
class) and provides data access to the database.
This procedure adds a new C# context class to the Models folder.
- Right-click the Models folder and then select Add -> New Item.
The Add New Item dialog box is displayed. - Select Class from the middle pane, name it ProductContext.cs and click Add.
Replace the default code contained in the class with the following code:
[!code-csharpMain]
1: using System.Data.Entity;
2: namespace WingtipToys.Models
3: {
4: public class ProductContext : DbContext
5: {
6: public ProductContext() : base("WingtipToys")
7: {
8: }
9: public DbSet<Category> Categories { get; set; }
10: public DbSet<Product> Products { get; set; }
11: }
12: }
This code adds the System.Data.Entity
namespace so that you have access to all the core functionality of Entity Framework, which includes the capability to query, insert, update, and delete data by working with strongly typed objects.
The ProductContext
class represents Entity Framework product database context, which handles fetching, storing, and updating Product
class instances in the database. The ProductContext
class derives from the DbContext
base class provided by Entity Framework.
Initializer Class
You will need to run some custom logic to initialize the database the first time the context is used. This will allow seed data to be added to the database so that you can immediately display products and categories.
This procedure adds a new C# initializer class to the Models folder.
- Create another
Class
in the Models folder and name it ProductDatabaseInitializer.cs. Replace the default code contained in the class with the following code:
[!code-csharpMain]
1: using System.Collections.Generic;
2: using System.Data.Entity;
3:
4: namespace WingtipToys.Models
5: {
6: public class ProductDatabaseInitializer : DropCreateDatabaseIfModelChanges<ProductContext>
7: {
8: protected override void Seed(ProductContext context)
9: {
10: GetCategories().ForEach(c => context.Categories.Add(c));
11: GetProducts().ForEach(p => context.Products.Add(p));
12: }
13:
14: private static List<Category> GetCategories()
15: {
16: var categories = new List<Category> {
17: new Category
18: {
19: CategoryID = 1,
20: CategoryName = "Cars"
21: },
22: new Category
23: {
24: CategoryID = 2,
25: CategoryName = "Planes"
26: },
27: new Category
28: {
29: CategoryID = 3,
30: CategoryName = "Trucks"
31: },
32: new Category
33: {
34: CategoryID = 4,
35: CategoryName = "Boats"
36: },
37: new Category
38: {
39: CategoryID = 5,
40: CategoryName = "Rockets"
41: },
42: };
43:
44: return categories;
45: }
46:
47: private static List<Product> GetProducts()
48: {
49: var products = new List<Product> {
50: new Product
51: {
52: ProductID = 1,
53: ProductName = "Convertible Car",
54: Description = "This convertible car is fast! The engine is powered by a neutrino based battery (not included)." +
55: "Power it up and let it go!",
56: ImagePath="carconvert.png",
57: UnitPrice = 22.50,
58: CategoryID = 1
59: },
60: new Product
61: {
62: ProductID = 2,
63: ProductName = "Old-time Car",
64: Description = "There's nothing old about this toy car, except it's looks. Compatible with other old toy cars.",
65: ImagePath="carearly.png",
66: UnitPrice = 15.95,
67: CategoryID = 1
68: },
69: new Product
70: {
71: ProductID = 3,
72: ProductName = "Fast Car",
73: Description = "Yes this car is fast, but it also floats in water.",
74: ImagePath="carfast.png",
75: UnitPrice = 32.99,
76: CategoryID = 1
77: },
78: new Product
79: {
80: ProductID = 4,
81: ProductName = "Super Fast Car",
82: Description = "Use this super fast car to entertain guests. Lights and doors work!",
83: ImagePath="carfaster.png",
84: UnitPrice = 8.95,
85: CategoryID = 1
86: },
87: new Product
88: {
89: ProductID = 5,
90: ProductName = "Old Style Racer",
91: Description = "This old style racer can fly (with user assistance). Gravity controls flight duration." +
92: "No batteries required.",
93: ImagePath="carracer.png",
94: UnitPrice = 34.95,
95: CategoryID = 1
96: },
97: new Product
98: {
99: ProductID = 6,
100: ProductName = "Ace Plane",
101: Description = "Authentic airplane toy. Features realistic color and details.",
102: ImagePath="planeace.png",
103: UnitPrice = 95.00,
104: CategoryID = 2
105: },
106: new Product
107: {
108: ProductID = 7,
109: ProductName = "Glider",
110: Description = "This fun glider is made from real balsa wood. Some assembly required.",
111: ImagePath="planeglider.png",
112: UnitPrice = 4.95,
113: CategoryID = 2
114: },
115: new Product
116: {
117: ProductID = 8,
118: ProductName = "Paper Plane",
119: Description = "This paper plane is like no other paper plane. Some folding required.",
120: ImagePath="planepaper.png",
121: UnitPrice = 2.95,
122: CategoryID = 2
123: },
124: new Product
125: {
126: ProductID = 9,
127: ProductName = "Propeller Plane",
128: Description = "Rubber band powered plane features two wheels.",
129: ImagePath="planeprop.png",
130: UnitPrice = 32.95,
131: CategoryID = 2
132: },
133: new Product
134: {
135: ProductID = 10,
136: ProductName = "Early Truck",
137: Description = "This toy truck has a real gas powered engine. Requires regular tune ups.",
138: ImagePath="truckearly.png",
139: UnitPrice = 15.00,
140: CategoryID = 3
141: },
142: new Product
143: {
144: ProductID = 11,
145: ProductName = "Fire Truck",
146: Description = "You will have endless fun with this one quarter sized fire truck.",
147: ImagePath="truckfire.png",
148: UnitPrice = 26.00,
149: CategoryID = 3
150: },
151: new Product
152: {
153: ProductID = 12,
154: ProductName = "Big Truck",
155: Description = "This fun toy truck can be used to tow other trucks that are not as big.",
156: ImagePath="truckbig.png",
157: UnitPrice = 29.00,
158: CategoryID = 3
159: },
160: new Product
161: {
162: ProductID = 13,
163: ProductName = "Big Ship",
164: Description = "Is it a boat or a ship. Let this floating vehicle decide by using its " +
165: "artifically intelligent computer brain!",
166: ImagePath="boatbig.png",
167: UnitPrice = 95.00,
168: CategoryID = 4
169: },
170: new Product
171: {
172: ProductID = 14,
173: ProductName = "Paper Boat",
174: Description = "Floating fun for all! This toy boat can be assembled in seconds. Floats for minutes!" +
175: "Some folding required.",
176: ImagePath="boatpaper.png",
177: UnitPrice = 4.95,
178: CategoryID = 4
179: },
180: new Product
181: {
182: ProductID = 15,
183: ProductName = "Sail Boat",
184: Description = "Put this fun toy sail boat in the water and let it go!",
185: ImagePath="boatsail.png",
186: UnitPrice = 42.95,
187: CategoryID = 4
188: },
189: new Product
190: {
191: ProductID = 16,
192: ProductName = "Rocket",
193: Description = "This fun rocket will travel up to a height of 200 feet.",
194: ImagePath="rocket.png",
195: UnitPrice = 122.95,
196: CategoryID = 5
197: }
198: };
199:
200: return products;
201: }
202: }
203: }
As you can see from the above code, when the database is created and initialized, the Seed
property is overridden and set. When the Seed
property is set, the values from the categories and products are used to populate the database. If you attempt to update the seed data by modifying the above code after the database has been created, you won’t see any updates when you run the Web application. The reason is the above code uses an implementation of the DropCreateDatabaseIfModelChanges
class to recognize if the model (schema) has changed before resetting the seed data. If no changes are made to the Category
and Product
entity classes, the database will not be reinitialized with the seed data.
[!NOTE]
If you wanted the database to be recreated every time you ran the application, you could use the
DropCreateDatabaseAlways
class instead of theDropCreateDatabaseIfModelChanges
class. However for this tutorial series, use theDropCreateDatabaseIfModelChanges
class.
At this point in this tutorial, you will have a Models folder with four new classes and one default class:
Configuring the Application to Use the Data Model
Now that you’ve created the classes that represent the data, you must configure the application to use the classes. In the Global.asax file, you add code that initializes the model. In the Web.config file you add information that tells the application what database you’ll use to store the data that’s represented by the new data classes. The Global.asax file can be used to handle application events or methods. The Web.config file allows you to control the configuration of your ASP.NET web application.
Updating the Global.asax file
To initialize the data models when the application starts, you will update the Application_Start
handler in the Global.asax.cs file.
[!NOTE]
In Solution Explorer, you can select either the Global.asax file or the Global.asax.cs file to edit the Global.asax.cs file.
Add the following code highlighted in yellow to the
Application_Start
method in the Global.asax.cs file.[!code-csharpMain]
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.Optimization;
6: using System.Web.Routing;
7: using System.Web.Security;
8: using System.Web.SessionState;
9: using System.Data.Entity;
10: using WingtipToys.Models;
11:
12: namespace WingtipToys
13: {
14: public class Global : HttpApplication
15: {
16: void Application_Start(object sender, EventArgs e)
17: {
18: // Code that runs on application startup
19: RouteConfig.RegisterRoutes(RouteTable.Routes);
20: BundleConfig.RegisterBundles(BundleTable.Bundles);
21:
22: // Initialize the product database.
23: Database.SetInitializer(new ProductDatabaseInitializer());
24: }
25: }
26: }
[!NOTE]
Your browser must support HTML5 to view the code highlighted in yellow when viewing this tutorial series in a browser.
As shown in the above code, when the application starts, the application specifies the initializer that will run during the first time the data is accessed. The two additional namespaces are required to access the Database
object and the ProductDatabaseInitializer
object.
Modifying the Web.Config File
Although Entity Framework Code First will generate a database for you in a default location when the database is populated with seed data, adding your own connection information to your application gives you control of the database location. You specify this database connection using a connection string in the application’s Web.config file at the root of the project. By adding a new connection string, you can direct the location of the database (wingtiptoys.mdf) to be built in the application’s data directory (App_Data), rather than its default location. Making this change will allow you to find and inspect the database file later in this tutorial.
- In Solution Explorer, find and open the Web.config file.
Add the connection string highlighted in yellow to the
<connectionStrings>
section of the Web.config file as follows:[!code-xmlMain]
1: <connectionStrings>
2: <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WingtipToys-20131119102907.mdf;Initial Catalog=aspnet-WingtipToys-20131119102907;Integrated Security=True"
3: providerName="System.Data.SqlClient" />
4: <add name="WingtipToys"
5: connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\wingtiptoys.mdf;Integrated Security=True"
6: providerName="System.Data.SqlClient" />
7: </connectionStrings>
When the application is run for the first time, it will build the database at the location specified by the connection string. But before running the application, let’s build it first.
Building the Application
To make sure that all the classes and changes to your Web application work, you should build the application.
From the Debug menu, select Build WingtipToys.
The Output window is displayed, and if all went well, you see a succeeded message.
If you run into an error, re-check the above steps. The information in the Output window will indicate which file has a problem and where in the file a change is required. This information will enable you to determine what part of the above steps need to be reviewed and fixed in your project.
Summary
In this tutorial of the series you have created the data model, as well as, added the code that will be used to initialize and seed the database. You have also configured the application to use the data models when the application is run.
In the next tutorial, you’ll update the UI, add navigation, and retrieve data from the database. This will result in the database being automatically created based on the entity classes that you created in this tutorial.
Additional Resources
Entity Framework Overview
Beginner’s Guide to the ADO.NET Entity Framework
Code First Development with Entity Framework (video)
Code First Relationships Fluent API
Code First Data Annotations
Productivity Improvements for the Entity Framework
|