ASP.NET 웹 API 튜 토리 얼 생 성 Admin 컨트롤 러 인 스 턴 스 공유
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}]
이 글 을 보고 얻 은 것 이 있다 면 추천 해 주 십시오.이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 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에 따라 라이센스가 부여됩니다.