ASP.NET Web API 튜 토리 얼 에서 도 메 인 모델 을 만 드 는 방법 에 대해 자세히 소개 합 니 다.
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 참조) 그림 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 만 필요 합 니 다.더 많은 정 보 는'순환 대상 참조 처리'를 참조 합 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
mavn 프로젝트 생 성my - app 디 렉 터 리 에 target 디 렉 터 리 를 하나 더 만 들 었 습 니 다. 3) 포장, 명령 행 에 들 어가 my - app 디 렉 터 리 로 전환, 명령 실행: mvc clean package...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.