ASP.NET Web API 튜 토리 얼 에서 도 메 인 모델 을 만 드 는 방법 에 대해 자세히 소개 합 니 다.

모델 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 Entity Object 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 방법 을 이용 하여 도 메 인 대상 은 트 랜 잭 션 처리,지속 화 등 추가 코드 가 필요 하지 않 습 니 다.(특히 엔 티 오 브 젝 트 류 에 물 려 받 을 필요 가 없다.)데이터 주석(data annotation)을 사용 하여 실체 프레임 워 크 를 어떻게 데이터베이스 방안 을 만 드 는 지 제어 할 수 있 습 니 다.POCOs do not carry any extra properties that describe database state,they can easily be serialized to JSON or XML.그러나,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 Order Detail 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 클래스 생 성 다음 구현 과 함께 제품 클래스 를 추가 합 니 다.제품 클래스(제품 클래스)를 다음 과 같이 추가 합 니 다
 
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; }
}
}
convention 에 의 해 Entity Framework 는 Id property 를 primary key 로 사용 하고 데이터베이스 테이블 의 identity column 에 maps it 를 사용 합 니 다.new Product instance 를 생 성 할 때 Id 에 대한 값 을 설정 하지 않 습 니 다.because the database generates the value.약정 에 따라 실체 프레임 워 크 는 Id 속성 을 메 인 키 로 하고 데이터베이스 시트 의 표지 열 로 표시 합 니 다.새 제품 인 스 턴 스 를 만 들 때 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 Order Detail class:Order Detail 클래스 추가(주문서 세부 클래스,또는 주문 상세 유형):
 
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; }
}
}
외국 키 관계 외부 키 관계 주문 에 많은 주문 세부 사항 이 포함 되 어 있 으 며 각 주문 세부 사항 은 하나의 제품 을 참조 합 니 다.이러한 관 계 를 나타 내기 위해 OrderDetail 클래스 는 OrderId 및 ProductId 라 는 속성 을 정의 합 니 다.엔 터 티 프레임 워 크 는 이러한 속성 이 외국 키 를 나타 내 는 것 으로 추정 합 니 다.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 include 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(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.현재 이 프로젝트 를 컴 파일 합 니 다.실체 프레임 워 크 는 반 사 를 통 해 이 모델 들 의 속성 을 발견 할 수 있 기 때문에 컴 파일 된 프로그램 집합 으로 해당 하 는 데이터 베이스 방안 을 만들어 야 한다(이곳 의 데이터 베이스 방안 은 데이터 베이스,표 구조 와 관계 등 데이터 베이스 방면 의 정의 인 번역자 주 를 말한다).미디어 형식 포맷 터 설정 구성 미디어 형식 포맷 터 는 웹 API 가 HTTP 응답 본문 을 작성 할 때 데 이 터 를 직렬 화 하 는 객체 입 니 다.내장 포맷 터 는 JSON 및 XML 출력 을 지원 합 니 다.기본적으로,both of these formatters serialize all objects by value.media-type(미디어 형식)포맷 기 는 웹 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 류 와 Order Detail 류 의 경우 입 니 다.모든 것 이 다른 인용 을 포함 하고 있 기 때 문 입 니 다.포맷 기 는 이 인용 을 따라 값 에 따라 모든 대상 을 써 서 순환 을 일 으 킬 수 있 습 니 다.따라서 우 리 는 이런 기본 행 위 를 수정 해 야 한다.In Solution Explorer, expand the App_Start folder and open the file named WebApiconfig.cs.Add the following code to the WebApiconfig class:"솔 루 션 자원 관리자"에서 AppStart 폴 더 를 열 고 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 만 필요 합 니 다.더 많은 정 보 는'순환 대상 참조 처리'를 참조 합 니 다.

좋은 웹페이지 즐겨찾기