+关注继续查看

# Part 2: Creating the Domain Models 第2部分：创建域模型

ework/using-web-api-with-entity-framework,-part-2

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.

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.

We will create the following POCOs:

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

Add a Product class with the following implementation:

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.

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属性必须是一个非空字符串。

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; }
// 导航属性
public ICollection<OrderDetail> OrderDetails { get; set; }
}
}

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; }
// 导航属性
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.

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.

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

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.

In Solution Explorer, expand the App_Start folder and open the file named WebApiConfig.cs. Add the following code to the WebApiConfig class:

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

windows批量创建用户

673 0
[ASP.NET]二维码的创建

886 0
IntelliJ IDEA 12 创建Web项目 教程 超详细版

1030 0
Json.Net系列教程 3.Json.Net序列化和反序列化设置

759 0
Java 并发/多线程教程(七)-创建和启动java线程
919 0
Json.Net系列教程 2.Net类型与JSON的映射关系

808 0
+关注

9798

2

《SaaS模式云原生数据仓库应用场景实践》

《看见新力量：二》电子书