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 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.
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.
Create the Data Access Layer的更多相关文章
- Apache Cloudstack Development 101 -- Data Access Layer
刚接触CloudStack,也是第一次翻译英文文档,限于水平有限,不当之处欢迎拍砖! 原文地址:https://cwiki.apache.org/confluence/display/CloudSta ...
- 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 NV ...
- Generic Data Access Layer泛型的数据访问层
http://www.codeproject.com/Articles/630277/Generic-Data-Access-Layer-GDA-Part-I http://www.codeproje ...
- Plugin with data access
In this tutorial I'll be using the nopCommerce plugin architecture to implement a product view track ...
- Spring.NET的中间数据层(Middle Tier Data Access)——事务管理(Transaction management)
简介 Spring.NET为事务管理提供了一个持久化抽象(consistent abstraction ),其优点如下: 为不同事务API,例如ADO.NET,Enterprise Services, ...
- EnterpriseLibrary 6.0(微软企业库6.0学习笔记) 之Data Access Block 配置和获取链接字符串
EnterpriseLibrary 的特点是快速开发,融合了微软工程师多年的经验,现在在微软内部有专门的一个小组在完善EnterpriseLibray,最近的更新时间是April 2013. 相关链接 ...
- Data access between different DBMS and other txt/csv data source by DB Query Analyzer
1 About DB Query Analyzer DB Query Analyzer is presented by Master Genfeng,Ma from Chinese Mainl ...
- FunDA(0)- Functional Data Access accessible to all
大数据.多核CPU驱动了函数式编程模式的兴起.因为函数式编程更适合多线程.复杂.安全的大型软件编程.但是,对许多有应用软件开发经验的编程者来说,函数式编程模式是一种全新的.甚至抽象的概念,可能需要很长 ...
- Enterprise Library - Data Access Application Block 6.0.1304
Enterprise Library - Data Access Application Block 6.0.1304 企业库,数据访问应用程序块 6.0.1304 企业库的数据访问应用程序块的任务简 ...
随机推荐
- [codevs3955]最长严格上升子序列(加强版)
题目大意:给你一个序列,要你求该序列中最长严格上升子序列的长度. 解题思路:此题算是一道LIS模板题.普通的$O(n^2)$的LIS是会TLE的,因为$n\le 1000000$,所以此题要用单调队列 ...
- Vue过渡与动画
通过 Vue.js 的过渡系统,可以在元素从 DOM 中插入或移除时自动应用过渡效果.Vue.js 会在适当的时机为你触发 CSS 过渡或动画,你也可以提供相应的 JavaScript 钩子函数在过渡 ...
- (51) magento集成增加到款通知
这篇主要讲述如何二开增加自己的功能,我没有继承方式二开,习惯是不好的,直接改了原来的模块. 达到效果就这样,当在网站支付成功,会同步到ERP系统中.下面来讲述实现过程 建立文件 payment_not ...
- 2015 Multi-University Training Contest 4 hdu 5336 XYZ and Drops
XYZ and Drops Time Limit: 3000/1500 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Tot ...
- CVE-2011-1473 tomcat
Per the bottom of: http://tomcat.apache.org/security-7.html#Not_a_vulnerability_in_Tomcat tweak you ...
- POJ——T 3041 Asteroids
http://poj.org/problem?id=3041 Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 23565 ...
- Datazen图表创建和公布
Datazen是被微软收购的移动端全平台的数据展现解决方式.此篇主要介绍怎样创建和公布图表. 如前面介绍,Datazen图表的创建和公布是通过Publisher的应用,它是Windows 8应用 ...
- 自己封装js组件 - 中级中高级
接着做关于alert组件的笔记 怎么又出来个中高级呢 对没错 就是出一个中高级来刷流量呵呵呵,但是中高级也不是白叫的 这次主要是增加了widget类,增加了自己绑定的事件和触发事件的方法!这么做是为什 ...
- WebAPI返回数据类型解惑 以及怎样解决Extjs无法解析返回的xml
最近开始使用WebAPI,上手很容易,然后有些疑惑 1.WebAPI默认返回什么数据类型,json还是xml? 2.怎么修改WebAPI的返回数据类型,我用IE浏览器请 求返回的数据都是JSON格式的 ...
- [HNOI2008] GT考试(DP+矩阵快速幂+KMP)
题目链接:https://www.luogu.org/problemnew/show/P3193#sub 题目描述 阿申准备报名参加 GT 考试,准考证号为 N 位数 X1,X2…Xn(0 <= ...