博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Create the Data Access Layer
阅读量:4966 次
发布时间:2019-06-12

本文共 7334 字,大约阅读时间需要 24 分钟。

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

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

 

 

 

 

 

 

转载于:https://www.cnblogs.com/chucklu/p/7122990.html

你可能感兴趣的文章
iOS7自定义statusbar和navigationbar的若干问题
查看>>
[Locked] Wiggle Sort
查看>>
deque
查看>>
Setting up a Passive FTP Server in Windows Azure VM(ReplyCode: 227, Entering Passive Mode )
查看>>
Python模块调用
查看>>
委托的调用
查看>>
c#中从string数组转换到int数组
查看>>
数据模型(LP32 ILP32 LP64 LLP64 ILP64 )
查看>>
java小技巧
查看>>
POJ 3204 Ikki's Story I - Road Reconstruction
查看>>
【BZOJ】2959: 长跑(lct+缩点)(暂时弃坑)
查看>>
iOS 加载图片选择imageNamed 方法还是 imageWithContentsOfFile?
查看>>
toad for oracle中文显示乱码
查看>>
SQL中Group By的使用
查看>>
错误org/aopalliance/intercept/MethodInterceptor解决方法
查看>>
Pylint在项目中的使用
查看>>
使用nginx做反向代理和负载均衡效果图
查看>>
access remote libvirtd
查看>>
(4) Orchard 开发之 Page 的信息存在哪?
查看>>
ASP.NET中 GridView(网格视图)的使用前台绑定
查看>>