Create the Data Access Layer

https://docs.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/create_the_data_access_layer

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 ProductIDProductNameDescriptionImagePathUnitPriceCategoryID, 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 CategoryIDCategoryNameDescription, and Products.

Each product will belong to one of the categories.

These entity classes will be added to the project‘s existing Models folder.

1.In Solution Explorer, right-click the Models folder and then select Add -> New Item.

2.Under Visual C# from the Installed pane on the left, select Code.

3.Select Class from the middle pane and name this new class Product.cs.

4.Click Add.
          The new class file is displayed in the editor.

5.Replace the default code with the following code:

6.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:

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.

1.Right-click the Models folder and then select Add -> New Item.
The Add New Item dialog box is displayed.

2.Select Class from the middle pane, name it ProductContext.cs and click Add.

3.Replace the default code contained in the class with the following code:

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.+

1.Create another Class in the Models folder and name it ProductDatabaseInitializer.cs.

2.Replace the default code contained in the class with the following code:

As you can see from the above code, when the database is created and initialized, the Seed property is overridden and set.

When the Seedproperty 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.

时间: 2024-10-13 11:55:05

Create the Data Access Layer的相关文章

专职DBA-MySQL DAL(Data Access Layer)中间件总结

MySQL DAL(Data Access Layer)中间件总结 DAL是数据访问层的英文缩写,即为数据访问层(Data Access Layer).用在这里可能不是特别恰当,因为本文主要介绍MySQL访问的中间件,不过也是属于DAL的范畴.本文不会去高可用相关的知识,主要聚焦于MySQL的横向扩展. 我们知道最简单的一种扩展是MySQL 主从复制,通过1主多从来实现读的性能扩展,但是这样的扩展不仅仅有局限性,而且写入的问题并没有解决.目前市场上用三类解决方案: 1.客户端分片(推荐) 程序客

csharp: Procedure with DAO(Data Access Object) and DAL(Data Access Layer)

sql script code: CREATE TABLE DuCardType ( CardTypeId INT IDENTITY(1,1) PRIMARY KEY, CardTypeName NVARCHAR(100) NOT NULL, --卡类名称 CardTypeColor NVARCHAR(50) NOT NULL --卡颜色(或样本) ) GO IF EXISTS (SELECT * FROM sysobjects WHERE [name] = 'proc_Insert_DuCar

Generic Data Access Layer泛型的数据访问层

http://www.codeproject.com/Articles/630277/Generic-Data-Access-Layer-GDA-Part-I http://www.codeproject.com/Articles/681565/Self-Synchronized-Data-Access-Layer?msg=5004433#xx5004433xx

Network 5: Data Link Layer

Some important issues related to Data Link Layer: Ethernet uses CSMA/CD with binary exponential backoff as multiple access control protocol, and stipulates the minimum frame length is 64 bytes. 以下代码纯属娱乐,如能运行,纯属巧合. 1 public void transmit() { 2 int col

[EntLib]微软企业库6 基于Data Access Application Block的Repository

名字起得有点夸张了,其实就是实现基于Data Access Application Block的DAL基类和约束 首先Repository部分没什么好描述的,如果有不了解的可以直接百度或者谷歌相关内容,直接上具体代码 注意此部分没有写批量查询的方法(比如FindAll,这跟后面的基类设定有关) /// <summary> /// DataAccess Repository /// </summary> /// <typeparam name="T1">

WIN7系统 64位出现 Net Framework 数据提供程序要求 Microsoft Data Access Components(MDAC).

WIN7系统 64位出现  Net Framework 数据提供程序要求 Microsoft Data Access Components(MDAC).请安装 Microsoft Data Access Components(MDAC)2.6或更高的版本.怎么解决,已经下载了2.8版本安装了,但是还是不顶用. 2015-12-02 10:51网友采纳 这应该是你安装的系统有精简过系统文件,导致安装一些程序缺乏文件出错.换个系统吧.可到我的系统贴吧下载GHO系统与GHO安装工具,可以在进入现在的系

[翻译]比较ADO.NET中的不同数据访问技术(Performance Comparison:Data Access Techniques)

Performance Comparison: Data Access Techniques Priya DhawanMicrosoft Developer Network January 2002 原文链接:https://msdn.microsoft.com/en-us/library/ms978388.aspx 概要:在典型的应用环境中,比较不同数据访问技术的表现性能.适用于Microsoft .NET Framework Beta2 和 Microsoft SQL Server 2000

跨数据存取控件Universal Data Access Components

最近发现MDT推出去的系统的有不同问题,其问题就不说了,主要是策略权限被域继承了.比如我们手动安装的很多东东都是未配置壮态,推的就默认为安全壮态了,今天细找了一下,原来把这个关了就可以了. 跨数据存取控件Universal Data Access Components

Enterprise Library - Data Access Application Block 6.0.1304

Enterprise Library - Data Access Application Block 6.0.1304 企业库,数据访问应用程序块 6.0.1304 企业库的数据访问应用程序块的任务简化了开发实现通用数据访问功能. 应用程序可以使用这个应用程序块在不同的情况下,例如读取数据显示,通过应用程序层传递数据,提交更改的数据的数据库系统. 安装企业库,数据访问应用程序块,运行以下命令 包管理器控制台 PM> Install-Package EnterpriseLibrary.Data h