代码特色:
- Entity Framework Code First
CodeFirst是EntityFramework 4.1后新增的一种映射方式
,在这种方式下,开发人员只需要编写代码,由ORM框架自动动创建模型和数据库
数据库则可看作类似于XML一样序列化的方式,非常简洁(由于开发人员可以无需关心数据库的具体结构,最初也有叫做CodeOnly的)。
Entity Framework Code First
试了下安装不成功:
提示针对的解决方案框架不符合。
而在2011四月发布的Entity Framework 4中存在三种工作方式,他们分别为:Code First, Model First和Database First
- Data Annotations 数据注释
- Strongly typed data controls 强类型数据控制
- Model binding 模型绑定
可以学到:
What you'll learn:
- How to create a shopping cart for the web application.
- How to enable users to add items to the shopping cart.
- How to add a GridView control to display shopping cart details.
- How to calculate and display the order total.
- How to remove and update items in the shopping cart.
- How to include a shopping cart counter.
1,给网页应用创建购物车
2,让用户给购物车增加项目
3,增加GridView控件来显示购物车详细资料
4,计算和显示订单总数
5,移除和更新购物车中的项目
6,引入购物车数量
创建购物车
之前,增加网页和代码从数据库中查看产品数据。
本次,将创建购物车来管理用户感兴趣的产品。即使用户没有注册和登录,也能浏览并向购物车增加项目。
管理购物车访问,用户第一次访问购物车的时候,将使用a globally unique identifier (GUID)给用户分配一个独立的ID。你会使用ASP.NET会话状态(Session state)存储此ID。
注意:ASP.NET会话状态是一个存储用户特定信息的方便的地方,当用户离开网站的时候将会失效。当误用session state,将会使得大型网站性能受到影响。使用会话状态的轻应用效果良好。本例程展示了没有外部提供者时,怎样使用session state。会话状态存储在托管网站的Web服务器的在内部进程中。
大型网站提供多个应用实例,或者在不同的服务器上运行一个应用的多个实例、考虑使用Windows Azure Cache Service
这个缓冲服务提供一种分布式缓冲服务,是一种外部到网站的分布式缓存服务并解决使用内部进程session state。
For more information see, How to Use ASP.NET Session State with Windows Azure Web Sites.
Add CartItem as a Model Class
之前的例子,通过在Models 文件夹中创建了Category
和 Product两个类,给
category 和 product 数据定义了图式(schema)。现在,增加一个类给购物车定义图式。后面,你将增加一个类来处理对CartItem表的数据访问。这个类将会增加对购物车中项目的增加、移除、更新。
CartItem类包含图式,用来定义每个产品的用户添加到购物车。这个图式与之前例子中的图式相似。
按惯例,Entity Framework Code First期望CartItem表的主键是CartItemId
或 ID。
然而,代码通过使用数据注释属性[Key]
重写了默认行为。ItemId 属性的[Key]属性
指定了ItemID属性为主键。CartId属性指定了用户的id,用以分配来购买东西。当用户访问购物车时,你将增加代码来创建用户id。
这个id也将被存储为
ASP.NET Session变量。
Update the Product Context
除了增加CartItem类,你会需要更新数据库内容类来管理实体类和提供对数据库的数据访问,做到这些,你将增加新创建的CartItem模型类到产品内容类中。
像之前实例中提到的那样,
ProductContext文件中的代码增加了System.Data.Entity命名空间以便你能访问
Entity Framework的所有核心功能。功能包括 通过使用强类型对象查询、插入、更新、删除数据的能力。ProductContext类增加了对新建的CartItem类的访问。
Managing the Shopping Cart Business Logic
下一步,你将在一个新的逻辑文件夹中创建ShoppingCart类。ShoppingCart类处理对CartItem表的数据访问。CartItem类也将包括 增加、移除、更新购物车中项目的业务逻辑。
你将要增加的购物车逻辑,将包含管理一下行为的能力:
1,向购物车中增加项目。
2,从购物车中移除项目。
3,获取购物车id。
4,获取购物车中的项目。
5,计算购物车项目的总量。
6,更新购物车数据。
购物车网页(ShoppingCart.aspx)和购物车类将一起使用来访问购物车中的数据。(ShoppingCart.aspx)网页将显示用户所有 的项目到购物车中。除了购物车网页和类,你将创建一个(AddToCart.aspx)网页来向购物车中增加产品。你也将向该网页(ShoppingCart.aspx),和ProductList.aspx网页中增加代码来提供一个到AddToCart.aspx页的链接,以便用户可以增加产品到购物车中。
The following diagram shows the basic process that occurs when the user adds a product to the shopping cart.
下面的代码展示了当用户向购物车中增加产品时发生的基本过程。
当用户点击了ProductList.aspx 页的,或者ProductDetails.aspx页的 Add To Cart链接,应用将会导航到AddToCart.aspx页,并自动到ShoppingCart.aspx页。AddToCart.aspx页会通过调用ShoppingCart类中的方法增加向购物车中选择产品,
ShoppingCart.aspx页将显示已经加入到购物车中的产品。
Creating the Shopping Cart Class
购物车类将增加到应用中的分文件夹以便将在model (Models folder)和pages (root folder)及logic (Logic folder)之间 有一个明显的区分。
Name the new folder Logic
- In Solution Explorer, right-click the WingtipToys project and select Add -> New Folder. Name the new folder Logic.
- Right-click the Logic folder and then select Add -> New Item.
- Add a new class file named ShoppingCartActions.cs.
- Replace the default code with the following code:
AddToCart方法使得独立的产品可以包括在基于产品id的购物车中。产品被加入到车中,或者如果车已经包含了一个那个产品的项目,数量得到增长。
GetCartId
方法为用户返回车的id号。车id用于跟踪 一个用户在他们购物车中的项目。如果用户没有存在的车id,一个新的车id会为他们创建。如果用户用注册的用户名登录,车
id被设置为他们的用户名。然而,如果用户没有登录,车id被设置为一个独有的值(一个GUID)。GUID保证基于 session,只为每个用户创建一个车号。GetCartItems
方法为用户返回一个购物车项目列表。该例子的后面,你将会看到模型绑定被用来在购物车中通过GetCartItems方法显示 购物车项目
Creating the Add-To-Cart Functionality
之前提到的,你将创建一个进程页命名为AddToCart.aspx,用来为用户向购物车中增加新的产品。该网页将调用刚刚创建的ShoppingCart
类中的
AddToCart
方法。
AddToCart.aspx 页将期望 有一个产品id传给它。 该产品id将在调用ShoppingCart
类中的AddToCart
方法的时候
被使用。
注:你将为该页调整 后端代码(AddToCart.aspx.cs),而不是page UI (AddToCart.aspx).
To create the Add-To-Cart functionality:
- In Solution Explorer, right-click the WingtipToysproject, click Add -> New Item.
The Add New Item dialog box is displayed. - Add a standard new page (Web Form) to the application named AddToCart.aspx.
- · In Solution Explorer, right-click the AddToCart.aspx page and then click View Code. The AddToCart.aspx.cs code-behind file is opened in the editor.
- · Replace the existing code in the AddToCart.aspx.cs code-behind with the following:
当AddToCart.aspx页加载后,产品id从查询字符串中被获取。下一步,一个购物车类的实例被创建且被用来调用之前例子中加入的AddToCart
方法。AddToCart方法包含在
ShoppingCartActions.cs文件中,包括增加选择产品到购物车或增加选择的产品数量的逻辑。如果产品没有被加入到购物车中,产品被增加到数据库的CartItem
表中。如果产品已经加入到购物车中,且用户增加了相同产品的多余的项目,CartItem表中的产品数量会增加。最后,该页重定向到
ShoppingCart.aspx页,这样你将在下一步增加,用户看到一个在购物车中更新的项目列表。
之前提到的,一个用户id被用来辨别被分配到特定用户的产品。这个id被增加到CartItem表中的一行,每次用户增加一个产品到购物车中。
Creating the Shopping Cart UI
The ShoppingCart.aspx page will display the products that the user has added to their shopping cart.显示用户增加到车中的产品。 It will also provide the ability to add, remove and update items in the shopping cart. 也提供增加,删除,更新车中项目的能力。
- In Solution Explorer,
right-click WingtipToys,
click Add
-> New Item.
The Add New Item dialog box is displayed. - Add a new page (Web Form) that includes a master page by selecting Web Form using Master Page. Name the new page ShoppingCart.aspx.
- Select Site.Master to attach the master page to the newly created .aspx page.
- In the ShoppingCart.aspx page, replace the existing markup with the following markup:
The ShoppingCart.aspx page includes a GridView control
named CartList
.
ShoppingCart.aspx 页包含 一个GridView控件。
This control uses model binding to bind the shopping cart data from the database to the GridView control.
该控件使用模板绑定来将 购物车数据从 数据库 绑定到GridView控件。
When you set the ItemType
property of the GridView
control, the data-binding expression Item
is available in the
markup of the control and the control becomes strongly typed.
当你设置了GridView控件的ItemType属性,控件标记的 数据绑定表达式项目 是可用的,且控件成为强类型对象。
As mentioned earlier
in this tutorial series, you can select details of the Item
object
using IntelliSense.
之前例子中提到的,有可以使用IntelliSense选详细的项目对象。
To configure a data control to use model binding to select
data, you set the SelectMethod
property of the control.
使用模型绑定来选择数据来配置数据控件,要设置控件的SelectMethod属性。
In the markup above, you set the SelectMethod
to use the GetShoppingCartItems method which returns a list of CartItem
objects.
在上面的标记中,使用GetShoppingCartItems方法 设置了SelectMethod方法,返回一个CartItem对象的列表。
The GridView data control calls the method at the appropriate time in the page life cycle and automatically binds the returned data.
GridView数据控件在网页的生命周期内的合适的时间调用 该方法,且自动绑定返回的数据。
The GetShoppingCartItems
method must still be
added.
GetShoppingCartItems方法必须增加。
Retrieving the Shopping Cart Items
Next, you add code to the ShoppingCart.aspx.cs code-behind to retrieve and populate the Shopping Cart UI.
向
ShoppingCart.aspx.cs中加入代码获取并填充购物车UI.
- In Solution Explorer, right-click the ShoppingCart.aspx page and then click View Code. The ShoppingCart.aspx.cs code-behind file is opened in the editor.
- Replace the existing code with the following:
As mentioned above, the GridView
data control
calls the GetShoppingCartItems
method at the appropriate time in
the page life cycle and automatically binds the returned data.
前面提到,GridView控件自动调用GetShoppingCartItems方法获取返回的数据。
The GetShoppingCartItems
method creates an instance of the ShoppingCartActions
object.
GetShoppingCartItems方法创建了一个ShoppingCartActions对象的实例。
Then, the code uses that instance to return the items in
the cart by calling the GetCartItems
method.
然后,代码使用实例通过GetCartItems
方法来返回车中的项目。
Adding Products to the Shopping Cart
When either the ProductList.aspx or the ProductDetails.aspx page is displayed, the user will be able to add the product to the shopping cart using a link.
当不管ProductList.aspx 显示还是 ProductDetails.aspx显示,用户将能使用链接增加产品到购物车中。
When they click the link, the application navigates to the processing page named AddToCart.aspx.
当他们点击链接,应用导航到名为AddToCart.aspx的进程页。
The AddToCart.aspx pagewill call the AddToCart
method in the ShoppingCart
class that you added earlier in this
tutorial. AddToCart.aspx页将调用ShoppingCart
类中的AddToCart方法,
Now, you’ll add an Add to Cart link to both the ProductList.aspx page and the ProductDetails.aspx page.
现在,你将增加一个 Add to Cart链接,到ProductList.aspx 和ProductDetails.aspx 页中。
This link will
include the product ID
that is retrieved from the database.
链接将包括用来从数据库中获取数据的产品id 。
- In Solution Explorer, find and open the page named ProductList.aspx.
- Add the markup highlighted in yellow to the ProductList.aspx page so that the entire page appears as follows:
Testing the Shopping Cart
Run the application to see how you add products to the shopping cart.
- Press F5 to run the application.
After the project recreates the database, the browser will open and show the Default.aspx page.
项目重新创建数据库后,浏览器将打开并且显示Default.aspx页。
- Select Cars from the category
navigation menu.
The ProductList.aspx page is displayed showing only products included in the “Cars” category.
从种类category导航菜单中选择车。ProductList.aspx页显示仅仅包含“Cars” category的产品。
- Click the Add to Cart link next to the first product listed (the convertible car).
The ShoppingCart.aspx page is displayed, showing the selection in your
shopping cart.
显示ShoppingCart.aspx页,在购物车中展示了选择的项目。
- View additional products by selecting Planes from the category navigation menu.
- Click the Add to Cart link next to the first product listed.
The ShoppingCart.aspx page is displayed with the additional item. - Close the browser.
又选了一个Planes项目到购物车中。
Calculating and Displaying the Order Total
In addition to adding products to the shopping cart, you
will add a GetTotal
method to the ShoppingCart
class
and display the total order amount in the shopping cart page.
除了增加购物车中的产品,还将在购物车ShoppingCart
类中 增加GetTotal方法,并显示购物车页中的总得订单数量。
- In Solution Explorer, open the ShoppingCartActions.cs file in the Logic folder.
- Add the following
GetTotal
method highlighted in yellow to theShoppingCart
class, so that the class appears as follows:
First, the GetTotal
method gets the ID of the
shopping cart for the user.
首先,GetTotal方法为用户获取购物车的id。
Then the method gets the cart total by multiplying the product price by the product quantity for each product listed in the cart.
然后,GetTotal方法 对于购物车中的每个产品列表, 通过产品价格乘以产品数量获得车的总数。
Note
The above code uses the nullable type “int?
”.
Nullable types can represent all the values of an underlying type, and also as
a null value. For more information see, Using Nullable
Types
上面代码使用nullable type “int?
”。空类型能表示所有基础类型的值。也作为一个空值。
Modify the Shopping Cart Display
Next you’ll modify the code for the ShoppingCart.aspx
page to call the GetTotal
method and display that total on the ShoppingCart.aspx
page when the page loads.
接下来,将修改 ShoppingCart.aspx页的代码,来调用GetTotal方法并当页面加载时显示
ShoppingCart.aspx页中的总数。代码写到Page_Load方法中。
- In Solution Explorer, right-click the ShoppingCart.aspx page and select View Code.
- In the ShoppingCart.aspx.cs
file, update the
Page_Load
handler by adding the following code highlighted in yellow:
When the ShoppingCart.aspx page loads, it loads the
shopping cart object and then retrieves the shopping cart total by calling the GetTotal
method of the ShoppingCart
class. If the shopping cart is empty, a
message to that effect is displayed.
Testing the Shopping Cart Total
Run the application now to see how you can not only add a product to the shopping cart, but you can see the shopping cart total.
运行应用,你不仅能增加一个产品到购物车中,但是你能看到购物车总数。
- Press F5 to run the application.
The browser will open and show the Default.aspx page. - Select Cars from the category navigation menu.
- Click the Add To Cart link next to
the first product.
The ShoppingCart.aspx page is displayed with the order total. 显示订单数量。
- · Add some other products (for example, a plane) to the cart.
- · The ShoppingCart.aspx page is displayed with an updated total for all the products you've added.
- Stop the running app by closing the browser window.
Adding Update and Checkout Buttons to the Shopping Cart
To allow the users to modify the shopping cart, you’ll add an Update button and a Checkout button to the shopping cart page. The Checkout button is not used until later in this tutorial series.
为了允许用户修改购物车,你将增加一个更新按钮和校验按钮到购物车页。Checkout按钮到后面才使用。
- In Solution Explorer, open the ShoppingCart.aspx page in the root of the web application project.
- To add the Update button and the Checkout button to the ShoppingCart.aspx page, add the markup highlighted in yellow to the existing markup, as shown in the following code:
When the user clicks the Update button, the UpdateBtn_Click event handler will be called. This event handler will call the code that you’ll add in the next step.
当用户点击了Update后,UpdateBtn_Click事件触发将被调用。这个事件处理将调用 你接下来加入的代码。
Next, you can update the code contained in the ShoppingCart.aspx.cs file to loop through the cart items and call the RemoveItem and UpdateItem methods.
接下来,你能更新包含在ShoppingCart.aspx.cs文件中的代码,调用RemoveItem和UpdateItem方法。
- In Solution Explorer, open the ShoppingCart.aspx.cs file in the root of the web application project.
- Add the following code sections highlighted in yellow to the ShoppingCart.aspx.cs file:
When the user clicks the Update button on the ShoppingCart.aspx page, the UpdateCartItems method is called.
用户点了ShoppingCart.aspx 页上的Update后,UpdateCartItems方法被调用。
The UpdateCartItems method gets the updated values for each item in the shopping cart.
UpdateCartItems方法为购物车中的每个项目获得了更新值。
Then, the
UpdateCartItems method calls the UpdateShoppingCartDatabase
method
(added and explained in the next step) to either add or remove items from the
shopping cart.
然后,UpdateCartItems方法调用UpdateShoppingCartDatabase方法。用于增加或删除项目。
Once the database
has been updated to reflect the updates to the shopping cart, the GridView control
is updated on the shopping cart page by calling the DataBind
method for the GridView.
一旦数据库被更新,反应更新到购物车,GridView控件通过GridView
的DataBind方法
更新购物页。
Also, the total order amount on the shopping cart page is updated to reflect the updated list of items.
购物车页中的总订单数量被更新反应到项目更新列表中。
Updating and Removing Shopping Cart Items
On the ShoppingCart.aspx page, you can see controls have been added for updating the quantity of an item and removing an item. Now, add the code that will make these controls work.
ShoppingCart.aspx页中,你可以看到控件已经加入来更新项目数量和移除一个项目。现在,增加代码来让这些控件工作。
- In Solution Explorer, open the ShoppingCartActions.cs file in the Logic folder.
- Add the following code highlighted in yellow to the ShoppingCartActions.cs class file:
The UpdateShoppingCartDatabase
method, called
from the UpdateCartItems
method on the ShoppingCart.aspx.cs
page, contains the logic to either update or remove items from the shopping
cart.
UpdateShoppingCartDatabase方法,调用
ShoppingCart.aspx.cs页中的UpdateCartItems方法,包含更新或移除的逻辑。
The UpdateShoppingCartDatabase
method iterates through all the rows within the shopping cart list.
UpdateShoppingCartDatabase方法迭代购物车清单中的行。
If a shopping cart item has been marked to be removed, or
the quantity is less than one, the RemoveItem
method is called.
如果购物车项目已经标记为移除,或数量少于一个,RemoveItem方法被调用。
Otherwise, the shopping cart item is checked for updates
when the UpdateItem
method is called.
否则,购物车项目被验证UpdateItem方法被调用的时候
来更新。
After the shopping cart item has been removed or updated, the database changes are saved.
购物车项目移除或更新之后,数据库改变被保存。
The ShoppingCartUpdates
structure is used to
hold all the shopping cart items.
ShoppingCartUpdates结构用来 控制所有的购物车项目。
The UpdateShoppingCartDatabase
method uses the
ShoppingCartUpdates
structure to determine if any of the items
need to be updated or removed.
UpdateShoppingCartDatabase方法使用ShoppingCartUpdates结构来决定是否任意的项目需要更新或者移除。
In the next tutorial, you will use the EmptyCart
method to clear the shopping cart after purchasing products.
下一个例子中,你将在购买完产品后使用EmptyCart方法来清除购物车。
But for now, you
will use the GetCount
method that you just added to the ShoppingCartActions.cs
file to determine how many items are in the shopping cart.
但现在,你将使用GetCount方法,仅增加
ShoppingCartActions.cs文件来决定购物车中有多少项目。
Adding a Shopping Cart Counter
To allow the user to view the total number of items in the shopping cart, you will add a counter to the Site.Master page. This counter will also act as a link to the shopping cart.
允许用户查看购物车中项目的总数,你将向Site.Master页中增加计数。这个计数也将作为一个到购物车中的链接。
- In Solution Explorer, open the Site.Master page.
- Modify the markup by adding the shopping cart counter link as shown in yellow to the navigation section so it appears as follows:
Before the page is rendered as HTML, the Page_PreRender
event is raised.
在网页被渲染为HTML之前,Page_PreRender事件被唤起。
In the Page_PreRender
handler, the total count
of the shopping cart is determined by calling the GetCount
method.
在Page_PreRender处理程序中,购物车总数 通过GetCount方法决定。
The returned value is added to the cartCount
span included in the markup of the Site.Master page.
返回值被增加到cartCount
span中。
包括
Site.Master页的标记。
The <span>
tags enables the inner elements to be properly rendered. When any page of the
site is displayed, the shopping cart total will be displayed.
<span>标记使得内部元素被合理的表达。当任意的网页显示,购物车总数将希纳斯。
The user can also click the shopping cart total to display the shopping cart.
用户也可以点击购物车总数来显示购物车。
Testing the Completed Shopping Cart
You can run the application now to see how you can add, delete, and update items in the shopping cart. The shopping cart total will reflect the total cost of all items in the shopping cart.
- Press F5 to run the
application.
The browser opens and shows the Default.aspx page. - Select Cars from the category navigation menu.
- Click the Add To Cart link
next to the first product.
The ShoppingCart.aspx page is displayed with the order total. - Select Planes from the category navigation menu.
- Click the Add To Cart link next to the first product.
- Set the quantity of the first item in the shopping cart to 3 and select the Remove Item check box of the second item.
- Click the Update button to update the shopping cart page and display the new order total.
Summary
In this tutorial, you have created a shopping cart for the Wingtip Toys Web Forms sample application. During this tutorial you have used Entity Framework Code First, data annotations, strongly typed data controls, and model binding.
The shopping cart supports adding, deleting, and updating items that the user has selected for purchase. In addition to implementing the shopping cart functionality, you have learned how to display shopping cart items in a GridView control and calculate the order total.
总结
这个例子中,你已经为Web Forms例子应用创建了一个购物车。本次已经使用了Entity Framework Code First,数据注释,强类型数据控件,模型绑定。
购物车支持增加,删,更新用户选择购买的项目。除了实现购物车功能,你已经学到怎样在GridView控件中显示购物车项目,并计算订单总数。
Checkout and Payment with PayPal
校验和付款。