ASP.NET Web API教程 创建域模型的方法详细介绍

 更新时间:2021年9月22日 10:18  点击:1595
添加模型
There are three ways to approach Entity Framework:
有三种方式使用实体框架:
Database-first: You start with a database, and Entity Framework generates the code.
Database-first(数据库先行):从一个数据库开始,然后实体框架生成相应代码。
Model-first: You start with a visual model, and Entity Framework generates both the database and code.
Model-first(模型先行):先从一个可视化模型开始,然后实体框架生成数据库和代码。
Code-first: You start with code, and Entity Framework generates the database.
Code-first(代码先行):先从代码开始,然后实体框架生成数据库。
We are using the code-first approach, so we start by defining our domain objects as POCOs (plain-old CLR objects). With the code-first approach, domain objects don't need any extra code to support the database layer, such as transactions or persistence. (Specifically, they do not need to inherit from the EntityObject class.) You can still use data annotations to control how Entity Framework creates the database schema.

我们打算使用code-first方法,因此,首先把域对象定义成POCO(plain-old CLR objects — 旧式无格式公共语言运行时(CLR)对象。很多人不太理解POCO对象,其实这种对象就像文本文件一样,是一种最简单、最原始、不带任何格式的对象。因此,在各种环境中最容易对这类对象进行处理,包括用各类语言进行处理 — 译者注)。利用code-first方法,域对象不需要任何附加代码去支持数据库层,如事务处理、持久化等。(特别是它们不需要继承于EntityObject类。)你仍可以使用数据注解(data annotation)对实体框架如何创建数据库方案进行控制。
Because POCOs do not carry any extra properties that describe database state, they can easily be serialized to JSON or XML. However, that does not mean you should always expose your Entity Framework models directly to clients, as we'll see later in the tutorial.
由于POCO不带描述数据库状态的任何附加属性,它们可以很容易地被序列化成JSON或XML。然而,这并不意味着你应当总是把实体框架模型直接暴露给客户端,就像我们稍后在本教程所看到的那样。

We will create the following POCOs:
我们将创建以下POCO:
Product
Order
OrderDetail
To create each class, right-click the Models folder in Solution Explorer. From the context menu, select Add and then select Class.
要创建每个类,在“解决方案资源管理器”中右击Models文件夹。从上下文菜单选择“添加”,然后选择“类”(如图2-14所示)。
WebAPI2-14 
图2-14. 创建POCO类
Add a Product class with the following implementation:
用以下实现添加一个Product类(产品类):
复制代码 代码如下:

namespace ProductStore.Models
{
using System.ComponentModel.DataAnnotations;
public class Product
{
[ScaffoldColumn(false)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public decimal Price { get; set; }
public decimal ActualCost { get; set; }
}
}

By convention, Entity Framework uses the Id property as the primary key and maps it to an identity column in the database table. When you create a new Product instance, you won't set a value for Id, because the database generates the value.
根据约定,实体框架用Id属性作为主键,并把它映射成数据库表中的标识列。当创建一个新的Product实例时,不必为Id设置值,因为数据库会生成它。
The ScaffoldColumn attribute tells ASP.NET MVC to skip the Id property when generating an editor form. The Required attribute is used to validate the model. It specifies that the Name property must be a non-empty string.
ScaffoldColumn(支架列)注解属性是告诉ASP.NET MVC,在生成编辑表单时,跳过这个Id属性。Required注解属性用于对模型进行验证。它指定Name属性必须是一个非空字符串。
注:本文把ScaffoldConlumn、Required等这一类英文中叫做Annotation Attribute的属性(Attribute)译为注解属性(Annotation Attribute),以便与类中的那些属性加以区别 — 译者注
Add the Order class:
添加Order类(订单类):
复制代码 代码如下:

namespace ProductStore.Models
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class Order
{
public int Id { get; set; }
[Required]
public string Customer { get; set; }
// Navigation property
// 导航属性
public ICollection<OrderDetail> OrderDetails { get; set; }
}
}

Add the OrderDetail class:
添加OrderDetail类(订单细节类,或订单详情类):
复制代码 代码如下:

namespace ProductStore.Models
{
public class OrderDetail
{
public int Id { get; set; }
public int Quantity { get; set; }
public int OrderId { get; set; }
public int ProductId { get; set; }
// Navigation properties
public Product Product { get; set; }
public Order Order { get; set; }
}
}

Foreign Key Relations
外键关系
An order contains many order details, and each order detail refers to a single product. To represent these relations, the OrderDetail class defines properties named OrderId and ProductId. Entity Framework will infer that these properties represent foreign keys, and will add foreign-key constraints to the database.
一份订单包含很多订单细节,而每个订单细节指向一个单一的产品。为了表示这些关系,OrderDetail类定义了名称为OrderId和ProductId的属性。实体框架将会推断出这些属性表示的是外键,并会把外键约束添加到数据库(见图2-15)。
WebAPI2-15 
图2-15. 外键关系
The Order and OrderDetail classes also include “navigation” properties, which contain references to the related objects. Given an order, you can navigate to the products in the order by following the navigation properties.
Order和OrderDetail类也包含了“导航(navigation)”属性,导航属性包含了对相关对象的引用。对于一份给定的订单,可以根据导航属性导航到这份订单的产品。
Compile the project now. Entity Framework uses reflection to discover the properties of the models, so it requires a compiled assembly to create the database schema.
现在,编译这个项目。实体框架会使用反射来发现这些模型的属性,因此它需要编译后的程序集来创建相应的数据库方案(这里的数据库方案意指数据库、表结构以及关系等数据库方面的定义 — 译者注)。
Configure the Media-Type Formatters
配置Media-Type格式化器
A media-type formatter is an object that serializes your data when Web API writes the HTTP response body. The built-in formatters support JSON and XML output. By default, both of these formatters serialize all objects by value.
media-type(媒体类型)格式化器是Web API书写HTTP响应体时对数据进行序列化的一个对象。内建的格式化器支持JSON和XML输出。默认地,这两种格式化都会按值序列化所有对象。
Serialization by value creates a problem if an object graph contains circular references. That's exactly the case with the Order and OrderDetail classes, because each holds a reference to the other. The formatter will follow the references, writing each object by value, and go in circles. Therefore, we need to change the default behavior.
如果对象图含有循环引用,按值序列化会出现问题。这恰好是Order类和OrderDetail类的情况,因为每一个都含有对另一个的引用。格式化器会遵循这些引用,按值写出每一个对象,于是会引起循环。因此,我们需要修改这种默认行为。
In Solution Explorer, expand the App_Start folder and open the file named WebApiConfig.cs. Add the following code to the WebApiConfig class:
在“解决方案资源管理器”中,展开App_Start文件夹,并打开名为WebApiConfig.cs的文件。将以下代码添加到这个WebApiConfig.cs类中(以下代码中的“新代码” — 译者注):
复制代码 代码如下:

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// New code:
// 新代码:
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}

This code sets the JSON formatter to preserve object references, and removes the XML formatter from the pipeline entirely. (You can configure the XML formatter to preserve object references, but it's a little more work, and we only need JSON for this application. For more information, see Handling Circular Object References.)
这段代码把JSON格式化器设置为防止对象引用(“新代码”第二行的作用 — 译者注),并把XML格式化器从管线(指HTTP的请求处理管线 — 译者注)中完全删除(“新代码”最后一行的作用 — 译者注)。(你也可以把XML格式化器配置成防止对象引用,但这还要做一点工作,而对于这个应用程序,我们只需要JSON。更多信息参阅“处理循环对象引用”
[!--infotagslink--]

相关文章

  • JavaScript动态创建div属性和样式示例代码

    1.创建div元素: Javascript代码 复制代码 代码如下: <scripttypescripttype="text/javascript"> functioncreateElement(){ varcreateDiv=document.createElement("div"); createDiv.innerHTML="Testcreateadiveleme...2013-10-13
  • JS创建Tag标签的方法详解

    这篇文章主要介绍了JS创建Tag标签的方法,结合具体实例形式分析了javascript动态操作页面HTML元素实现tag标签功能的步骤与相关操作技巧,需要的朋友可以参考下...2017-06-15
  • 什么是cookie?js手动创建和存储cookie

    什么是cookie? cookie 是存储于访问者的计算机中的变量。每当同一台计算机通过浏览器请求某个页面时,就会发送这个 cookie。你可以使用 JavaScript 来创建和取回 cookie 的值。 有关cookie的例子: 名字 cookie 当访...2014-05-31
  • PS如何创建变形文字 ps给文字变形的方法

    PS怎么创建变形文字?ps中想要给输入的文字变形,该怎么调整文字的显示形态呢?下面我们就来看看ps给文字变形的方法,需要的朋友可以参考下 我们在图层上输入文字后,可以...2017-07-06
  • idea 无法创建Scala class 选项的原因分析及解决办法汇总

    这篇文章主要介绍了idea 无法创建Scala class 选项的解决办法汇总,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-09-02
  • php创建无限级树型菜单

    写递归函数,可考虑缓存,定义一些静态变量来存上一次运行的结果,多程序运行效率很有帮助.。 大概步骤如下: step1:到数据库取数据,放到一个数组, step2:把数据转化为一个树型状的数组, step3:把这个树型状的数组转为html代码。...2015-11-08
  • Drupal模块开发之创建自己的钩子

    Drupal可以让第三方模块创建自己的钩子。在通常的实践中,有两种类型的钩子你可能想要创建,一种是内容修改类的钩子,一种是拦截类的钩子。 Drupal的钩子系统允许和模...2016-11-25
  • javascript创建对象的几种模式介绍

    下面小编就为大家带来一篇javascript创建对象的几种模式介绍。小编觉得挺不错的,现在分享给大家,也给大家做个参考...2016-05-09
  • C#创建Windows服务的实现方法

    这篇文章主要介绍了C#创建Windows服务的实现方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • C#对Word文档的创建、插入表格、设置样式等操作实例

    今天小编就为大家分享一篇C#对Word文档的创建、插入表格、设置样式等操作实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-06-25
  • C#动态创建button的方法

    这篇文章主要介绍了C#动态创建button的方法,涉及C#按钮属性动态设置的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • 详解js创建对象的几种方式和对象方法

    这篇文章主要介绍了详解js创建对象的几种方式和对象方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-01
  • 在java中使用SPI创建可扩展的应用程序操作

    这篇文章主要介绍了在java中使用SPI创建可扩展的应用程序操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-14
  • 浅析在javascript中创建对象的各种模式

    下面小编就为大家带来一篇浅析在javascript中创建对象的各种模式。小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-05-09
  • C#创建、部署、调用WebService图文实例详解

    本文主要用详细的图文给大家介绍C#创建、部署、调用WebService的全部过程以及中间需要避免的问题。...2020-06-25
  • JS动态创建元素的两种方法

    这篇文章主要为大家详细介绍了JS动态创建元素的两种方法,字符串拼接形式,或是使用Document、Element对象自带的一些函数 ,需要的朋友可以参考下...2016-04-22
  • 动态创建按钮的JavaScript代码

    本文给大家分享一段JS实例代码介绍动态创建按钮的方法,需要的朋友参考下本文...2016-02-01
  • Illustrator创建繁复之美的曼陀罗图案绘制教程

    今天小编在这里就来给Illustrator的这一款软件的使用者们来说一说创建繁复之美的曼陀罗图案的绘制教程,各位想知道具体信息的使用者们,那么下面就快来跟着小编一起看一...2016-09-14
  • 详细分析Javascript中创建对象的四种方式

    这篇文章详细介绍了Javascript中创建对象的几种方式与每种方式的优缺点,其中包括工厂模式、构造函数模式、原型模式和组合使用构造函数模式和原型模式,有需要的小伙伴们一起来学习学习吧。...2016-08-24
  • php WEB上创建网站

    我们用php来控制iis并且,在WEB上创建网站,管理删除等功能哦。 <? # PHP控制站点程序 # # 编写人:韩湘子 # # 邮箱:hanxiangzi@gmail.com # # MSN:hanx...2016-11-25