欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-06 14:46:50
添加模型 there are three ways to approach entity framework: 有三种方式使用实体框架: database-first: y...
添加模型
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所示)。
ASP.NET Web API教程 创建域模型的方法详细介绍 
图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)。
ASP.NET Web API教程 创建域模型的方法详细介绍 
图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。更多信息参阅“处理循环对象引用”