ASP.NET 웹 API 튜 토리 얼 생 성 Admin 컨트롤 러 인 스 턴 스 공유

이 섹 션 에 서 는 CRUD(create,read,update,and delete)operations on products 를 지원 하 는 웹 API controller 를 추가 합 니 다.The controller will use Entity Framework to communication with the database layer.Only administrators will be able to use this controller.고객 은 다른 컨트롤 러 를 통 해 제품 에 액세스 합 니 다.이 소절 에서,CRUD(생 성,읽 기,업데이트,삭제)작업 을 지원 하 는 웹 API 컨트롤 러 를 추가 하려 고 합 니 다.이 컨트롤 러 는 실체 프레임 워 크 를 사용 하여 데이터베이스 층 과 통신 할 것 이다.관리자 만 이 컨트롤 러 를 사용 할 수 있 습 니 다.클 라 이언 트 는 다른 컨트롤 러 를 통 해 제품 에 접근 할 것 이다.Solution Explorer,right-click the Controllers folder.Select Add and then Controller.'솔 루 션 자원 관리자'에서 Controllers 폴 더 를 오른쪽 클릭 하고'추가'를 선택 한 다음'컨트롤 러'를 선택 하 십시오(그림 2-16 참조).WebAPI2-16  그림 2-16.컨트롤 러 추가 하기 Add Controller dialog,name the controller AdminController.Under Template,select"API controller with read/write actions,using Entity Framework".Under Model class,select"Product(ProductStore.Models)".Under Data Context 에서""를 선택 합 니 다."컨트롤 러 추가"대화 상자 에서,이 컨트롤 러 를 Admin Controller 라 고 명명 합 니 다.'템 플 릿'아래 에서'읽 기/쓰기 동작 이 있 는 API 컨트롤 러(실체 프레임 워 크 로)'를 선택 하 십시오.'모델 클래스'에서'Product(ProductStore.Models)'를 선택 하 십시오.'데이터 컨 텍스트'에서'새로운 데이터 컨 텍스트'를 선택 하 십시오(그림 2-17 참조).WebAPI2-17  그림 2-17.컨트롤 러 대화 상자 의 설정 If the Model class drop-down does not show any model classes,make sure you compiled the project.Entity Framework uses reflection,so it needs the compiled assembly.'모델 클래스'드 롭 다운 목록 에 모델 클래스 가 표시 되 지 않 으 면 이 항목 이 컴 파일 되 었 는 지 확인 하 십시오.실체 프레임 워 크 는 반 사 를 사용 하기 때문에 컴 파일 된 프로그램 집합 이 필요 합 니 다.Selecting""will open the New Data Context dialog.Name the data context ProductStore.Models.Orders Context."<새 데이터 컨 텍스트>"를 선택 하면"새 데이터 컨 텍스트"대화 상 자 를 엽 니 다.이 데이터 컨 텍스트 를 ProductStore.Models.Orders Context 라 고 명명 합 니 다(그림 2-18 참조).WebAPI2-18  그림 2-18."새 데이터 컨 텍스트"클릭 OK to dismiss the New Data Context dialog.In the Add Controller dialog,click Add."OK"를 누 르 면 이"새 데이터 컨 텍스트"대화 상 자 를 종료 합 니 다.'컨트롤 러 추가'대화 상자 에서'추가'를 누 르 십시오.Here's what got added to the project:다음은 프로젝트 에 추 가 된 내용 입 니 다.A class named Orders Context that derives from DbContext.This class provides the glue between the POCO models and the database.이름 은 Orders Context 클래스 로 DbContext 에서 파생 됩 니 다.이 종 류 는 POCO 모델 과 데이터베이스 간 의 접착 을 제공 합 니 다.A Web API controller named AdminController.This controller supports CRUD operations on Product instances.It uses the Orders Context class to communication with Entity Framework.AdminController 라 는 웹 API 컨트롤 러이 컨트롤 러 는 제품 인 스 턴 스 의 CRUD 작업 을 지원 합 니 다.이 는 Orders Context 류 를 사용 하여 실체 프레임 워 크 와 통신 합 니 다.A new database connection string in the Web.config file.웹.config 파일 의 새로운 데이터베이스 연결 문자열 입 니 다.상술 한 새로운 추가 항목 은 그림 2-19 참조.WebAPI2-19  그림 2-19.항목 에 새로 추 가 된 내용 Open the Orders Context.cs file.Notice that the constructor specifies the name of the database connection string.This name reference to the connection string that was added to Web.config.Orders Context.cs 파일 을 엽 니 다.구조 기 는 데이터베이스 연결 문자열 의 이름 을 가리 키 고 있 습 니 다.이 이름 은 웹 config 에 추 가 된 연결 문자열 을 말 합 니 다.
 
public OrdersContext() : base("name=OrdersContext")Add the following properties to the OrdersContext class:
은 Orders Context 클래스 에 다음 속성 을 추가 합 니 다.
 
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
A DbSet representes a set of entities that can be queried.Here is the complete listing for the Orders Context class:DbSet 은 조회 할 수 있 는 실 체 를 표시 합 니 다.다음은 이 Orders Context 클래스 의 전체 목록 입 니 다.
 
public class OrdersContext : DbContext
{
public OrdersContext() : base("name=OrdersContext")
{
}
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
public DbSet<Product> Products { get; set; }
}
The AdminController class defines five methods that implement basic CRUD functionality.Each method corresponses to a URI that the client can invoke:클래스 는 기본 적 인 CRUD 기능 을 실현 하 는 다섯 가지 방법 을 정의 합 니 다.각 방법 은 클 라 이언 트 가 요청 할 수 있 는 URI(표 2-2 참조)에 대응 합 니 다.표 2-2.AdminController 에서 CRUD 작업 을 수행 하 는 다섯 가지 방법 table Each method calls into Orders Context to query the database.The methods that modify the collection(PUT,POST,and DELETE)calldb.SaveChanges to persist the changes to the database.Controllers are created per HTTP request and then disposed,so it is necessary to persist changes before a method returns.모든 방법 호출 은 Orders Context 에 들 어가 데이터 라 이브 러 리 를 조회 합 니 다.데이터 세트 를 수정 하 는 방법(PUT,POST,DELETE)은 db.SaveChanges 를 호출 하여 이 수정 을 데이터베이스 로 영구적 으로 되 돌 릴 수 있 도록 합 니 다.모든 HTTP 요청 은 컨트롤 러(인 스 턴 스)를 만 들 고 지 웁 니 다.따라서 한 가지 방법 으로 돌아 가기 전에 지속 화 를 수정 하 는 것 이 필요 하 다.데이터베이스 초기 화 기 를 추가 합 니 다.데이터베이스 초기 화 기 를 추가 합 니 다.Entity Framework 는 시작 시 데이터 베 이 스 를 채 우 고 모델 이 변 경 될 때마다 자동 으로 데이터 베 이 스 를 다시 만 들 수 있 는 좋 은 기능 을 가지 고 있 습 니 다.이 기능 은 항상 테스트 데이터 가 있 기 때문에 개발 중 에 유용 합 니 다.even if you change the models.실체 프레임 워 크 는(응용 프로그램)시작 할 때 데이터 베 이 스 를 채 우 고 모델 이 수정 되 었 을 때 데이터 베 이 스 를 재 구축 하 는 좋 은 기능 을 가지 고 있 습 니 다.이 특성 은 개발 기간 에 유용 하 다.왜냐하면 당신 은 항상 테스트 데이터 가 있 고 심지어 모델 을 수정 할 수 있 기 때문이다.Solution Explorer,right-click the Models folder and create a new class named Orders ContextInitializer.Paste in the following implementation:"솔 루 션 자원 관리자"에서 Models 폴 더 를 오른쪽 클릭 하고 Orders ContextInitializer 라 는 새로운 종 류 를 만 듭 니 다.다음 구현 을 붙 여 넣 기:
 
namespace ProductStore.Models
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
public class OrdersContextInitializer : DropCreateDatabaseIfModelChanges<OrdersContext>
{
protected override void Seed(OrdersContext context)
{
var products = new List<Product>()
{
new Product() { Name = "Tomato Soup", Price = 1.39M, ActualCost = .99M },
new Product() { Name = "Hammer", Price = 16.99M, ActualCost = 10 },
new Product() { Name = "Yo yo", Price = 6.99M, ActualCost = 2.05M }
};
products.ForEach(p => context.Products.Add(p));
context.SaveChanges();
var order = new Order() { Customer = "Bob" };
var od = new List<OrderDetail>()
{
new OrderDetail() { Product = products[0], Quantity = 2, Order = order},
new OrderDetail() { Product = products[1], Quantity = 4, Order = order }
};
context.Orders.Add(order);
od.ForEach(o => context.OrderDetails.Add(o));
context.SaveChanges();
}
}
}
DropCreateDatabaseIfModelChanges 클래스 로부터 상 속 받 아 모델 클래스 를 수정 할 때마다 Entity Framework 에 데이터 베 이 스 를 드 롭 하 라 고 말 합 니 다.Entity Framework 가 데이터 베 이 스 를 생 성(또는 다시 생 성)할 때,it calls the Seed method to populate the tables.We use the Seed method to add some example products plus an example order.DropCreate DatabaseIfModelChanges 류 에 대한 계승 을 통 해 우 리 는 실체 프레임 워 크 에 모델 류 를 언제든지 수정 하면 데이터 베 이 스 를 삭제 하 라 고 알려 주 고 있 습 니 다.실체 프레임 워 크 가 데이터 베 이 스 를 만 들 거나 재 구축 할 때 Seed 방법 으로 데이터 베 이 스 를 채 웁 니 다.우 리 는 이 Seed 방법 으로 예 제품 과 예 주문 서 를 추가 했다.This feature is great for testing,but don't use the DropCreate DatabaseIfModelChanges class in production,because you could lose your data if someone changes a model class.이 기능 은 테스트 에 좋 지만 제품(정식 실행 되 는 응용 프로그램-번역자 주)에 서 는 이 DropCreate DatabaseIfModelChanges 클래스 를 사용 하지 마 십시오.모델 류 를 수정 한 사람 이 있 으 면 데 이 터 를 잃 어 버 리 기 때문이다.Next, open Global.asax and add the following code to the Application_Start method:다음 단계 에서 Global.sax 를 열 고 다음 코드 를 application 에 추가 합 니 다.Start 방법:
 
System.Data.Entity.Database.SetInitializer(
new ProductStore.Models.OrdersContextInitializer());Send a Request to the Controller
컨트롤 러 에 요청 보 내기 이 시점 에서,we haven't written any client code,but you can invoke the web API using a web browser or an HTTP debugging tool such as Fiddler.Visual Studio 에서 press F5 to start debugging.Your web browser will open tohttp://localhost:portnum/여기 서 portnum 은 일부 포트 번호 입 니 다.지금,우 리 는 아직 클 라 이언 트 코드 를 작성 하지 않 았 지만,웹 브 라 우 저 나 Fiddler 와 같은 디 버 깅 도 구 를 사용 하여 이 웹 API 를 호출 할 수 있 습 니 다.Visual Studio 에서 F5 키 를 누 르 면 디 버 깅 을 시작 합 니 다.브 라 우 저 에서 웹 주 소 를 엽 니 다.http://localhost:portnum/여기,portnum 은 어떤 포트 번호 입 니 다.Send an HTTP request to "http://localhost:portnum/api/admin".첫 번 째 request may be slow to complete,because Entify Entity Framework needs to create and seed the database.응답 should something similar to the following:HTTP 요청 을 보 냅 니 다."http://localhost:portnum/api/admin”。첫 번 째 요청 은 좀 느 려 야 완 성 될 수 있 습 니 다.실체 프레임 워 크 는 데이터 베 이 스 를 만 들 고 재배 해 야 하기 때 문 입 니 다.그 응답 은 다음 과 같 아야 합 니 다.
 
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Mon, 18 Jun 2012 04:30:33 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: application/json; charset=utf-8
Content-Length: 175
Connection: Close
[{"Id":1,"Name":"Tomato Soup","Price":1.39,"ActualCost":0.99},{"Id":2,"Name":"Hammer",
"Price":16.99,"ActualCost":10.00},{"Id":3,"Name":"Yo yo","Price":6.99,"ActualCost":
2.05}]
이 글 을 보고 얻 은 것 이 있다 면 추천 해 주 십시오.

좋은 웹페이지 즐겨찾기