Entity Framework Code First Approach ASP.NET Repository Pattern을 사용하여 Web API 만들기
이 문서에서는 리포지토리 패턴과 Entity Framework 코드 우선 접근 방식을 사용하여 ASP.NET Web API를 만드는 방법을 알아봅니다.
이 문서에서는 리포지토리 패턴과 Entity Framework 코드 우선 접근 방식을 사용하여 ASP.NET Web API를 만드는 방법을 알아봅니다.
기본적으로 다음 방법을 배우게 됩니다.
- 엔티티와 저장소 인터페이스를 포함 할 핵심 프로젝트를 만듭니다.
- Entity Framework 코드 우선 접근 방식을 사용하여 데이터베이스 작업 코드를 포함하는 인프라 프로젝트를 만듭니다.
- 엔터티에서 CRUD 작업을 수행하는 웹 API를 만듭니다.
- jQuery 애플리케이션에서 웹 API를 사용하고 Ignite UI 차트에서 데이터를 렌더링합니다.
리포지토리 패턴이란 무엇입니까?
먼저 리포지토리 패턴이 필요한 이유를 이해하겠습니다. 리포지토리 패턴을 따르지 않고 데이터를 직접 사용하는 경우 다음과 같은 문제가 발생할 수 있습니다.
- Duplicate code
- 캐싱과 같은 데이터 관련 로직 또는 정책을 구현하기 어려움
- 데이터 액세스 계층이 없는 상태에서 비즈니스 로직을 단위 테스트하는 데 어려움이 있습니다.
- 긴밀하게 결합된 비즈니스 로직과 데이터베이스 액세스 로직
리포지토리 패턴을 구현하면 위의 문제를 방지하고 다음과 같은 이점을 얻을 수 있습니다.
- 비즈니스 로직은 데이터 액세스 로직 없이 단위 테스트를 수행할 수 있습니다.
- 데이터베이스 액세스 코드를 재사용할 수 있습니다.
- 데이터베이스 액세스 코드는 중앙에서 관리되므로 캐싱과 같은 모든 데이터베이스 액세스 정책을 쉽게 구현할 수 있습니다.
- domain logics를 쉽게 구현할 수 있습니다.
- 도메인 엔터티 또는 비즈니스 엔터티는 주석과 함께 강력한 형식입니다.
이제 얼마나 훌륭한지 나열했으므로 ASP.NET Web API에 리포지토리 패턴을 이식해 보겠습니다.
핵심 프로젝트 만들기
핵심 프로젝트에서는 엔터티와 리포지토리 인터페이스를 유지해야 합니다. 이 예에서는 City 엔터티를 사용하겠습니다. 따라서 아래 목록과 같이 City 클래스를 만들어 보겠습니다.
using System.ComponentModel.DataAnnotations; namespace WebApiRepositoryPatternDemo.Core.Entities { public class City { public int Id { get; set; } [Required] public string Name { get; set; } public string Country { get; set; } public int Population01 { get; set; } public int Population05 { get; set; } public int Population10 { get; set; } public int Population15 { get; set; } } }
보시다시피 System.ComponentModel.DataAnnotations의 일부인 Required 속성을 사용하여 데이터에 주석을 달고 있습니다. 두 가지 접근 방식 중 하나를 사용하여 도시 엔터티에 주석을 넣을 수 있습니다.
- System.ComponentModel.DataAnnotations 사용
- Using the Entity Framework Fluent API
두 방법 모두 고유한 장점이 있습니다. 도메인 엔터티에 대한 제한이 도메인의 일부라고 생각되면 핵심 프로젝트에서 데이터 주석을 사용합니다. 그러나 제한 사항이 데이터베이스와 관련이 있고 Entity Framework를 데이터베이스 기술로 사용하는 경우 유창한 API를 사용하십시오.
다음으로 저장소 인터페이스를 만들어 보겠습니다. City 엔터티에서 수행하려는 모든 작업은 리포지토리 인터페이스의 일부여야 합니다. ICityRepository 인터페이스는 아래 목록과 같이 만들 수 있습니다.
using System.Collections.Generic; using WebApiRepositoryPatternDemo.Core.Entities; namespace WebApiRepositoryPatternDemo.Core.Interfaces { public interface ICityRepository { void Add(City b); void Edit(City b); void Remove(string Id); IEnumerable<City> GetCity(); City FindById(int Id); } }
Core 프로젝트에는 데이터베이스 작업과 관련된 코드가 포함되어서는 안 됩니다. 따라서 다음 참조는 핵심 프로젝트의 일부가 되어서는 안 됩니다.
- 외부 라이브러리에 대한 참조
- 모든 데이터베이스 라이브러리에 대한 참조
- LINQ to SQL, 엔티티 프레임 워크 등과 같은 ORM에 대한 참조
엔터티 클래스와 리포지토리 인터페이스를 추가한 후 핵심 프로젝트는 아래 이미지와 같아야 합니다.

인프라 프로젝트 만들기
인프라 프로젝트에서는 애플리케이션 외부와 관련된 작업을 수행합니다. 예를 들어:
- Database operations
- 웹 서비스 사용
- 파일 시스템 액세스
데이터베이스 작업을 수행하기 위해 Entity Framework Code First 접근 방식을 사용합니다. CRUD 작업을 수행해야 하는 도시 엔터티를 이미 생성했습니다. 기본적으로 CRUD 작업을 사용하도록 설정하려면 다음 클래스가 필요합니다.
- DataContext class
- 핵심 프로젝트에서 생성된 Repository 인터페이스를 구현하는 Repository 클래스
- DataBaseInitalizer class
그런 다음 인프라 프로젝트에 다음 참조를 추가해야 합니다.
- Entity 프레임워크에 대한 참조입니다. 이를 추가하려면 프로젝트를 마우스 오른쪽 버튼으로 클릭하고 Nuget 패키지 관리를 클릭 한 다음 Entity Framework를 설치하십시오.
- 핵심 프로젝트에 대한 참조
DataContext class
In the DataContext class:
- City 엔터티에 대한 테이블을 만드는 DbSet 속성을 만듭니다.
- DataContext 클래스의 생성자에서 데이터베이스가 생성될 연결 문자열 이름을 전달합니다
- CityDataContext class will inherit the DbContext class
CityDataContext 클래스는 아래 목록과 같이 만들 수 있습니다.
using System.Data.Entity; using WebApiRepositoryPatternDemo.Core.Entities; namespace WebApiRepositoryPatternDemo.Infrastructure { public class CityDataContext : DbContext { public CityDataContext() : base("name=cityconnectionstring") { } public IDbSet<City> Cities { get; set; } } }
필요에 따라 연결 문자열을 전달하거나 Entity Framework를 사용하여 데이터베이스를 만들 수 있습니다. 인프라 프로젝트의 app.config에서 연결 문자열을 설정합니다. 계속해서 아래 목록과 같이 연결 문자열을 설정해 보겠습니다.
<connectionStrings> <add name="cityconnectionstring" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=CityPolulation;Integrated Security=True;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/> </connectionStrings>
데이터베이스 초기화 클래스
생성 시 데이터베이스에 몇 가지 초기 값을 제공하기 위해 데이터베이스 초기화 클래스를 만들어야 합니다. Database initialize 클래스를 만들려면 클래스를 만들고 DropCreateDatabaseIfModelChnages에서 상속합니다. 여기서는 모델이 변경될 경우 데이터베이스를 다시 만들 수 있도록 값을 설정합니다. Entity Framework의 다른 옵션도 탐색하고 cross ponding 클래스에서 데이터베이스 initialize 클래스를 상속할 수 있습니다. Seed 메서드에서 Cities 테이블의 초기 값을 설정할 수 있습니다. 3개 도시의 레코드를 사용하여 아래 목록과 같이 Database 이니셜라이저 클래스를 만들 수 있습니다.
using System.Data.Entity; using WebApiRepositoryPatternDemo.Core.Entities; namespace WebApiRepositoryPatternDemo.Infrastructure { public class CityDbInitalize : DropCreateDatabaseIfModelChanges<CityDataContext> { protected override void Seed(CityDataContext context) { context.Cities.Add(new City { Id=1, Country="India", Name="Delhi", Population01=20, Population05=22, Population10=25, Population15=30 }); context.Cities.Add(new City { Id=2, Country="India", Name="Gurgaon", Population01=10, Population05=18, Population10=20, Population15=22 }); context.Cities.Add(new City { Id=3, Country="India", Name="Bangalore", Population01=8, Population05=20, Population10=25, Population15=28 }); context.SaveChanges(); base.Seed(context); } } }
Repository class
지금까지 DataContext 및 DatabaseInitalize 클래스를 만들었습니다. 리포지토리 클래스에서 DataContext 클래스를 사용합니다. CityRepository 클래스는 핵심 프로젝트에서 ICityRepository 인터페이스를 구현하고 DataContext 클래스를 사용하여 CRUD 작업을 수행합니다. CityRepository 클래스는 아래 목록과 같이 구현할 수 있습니다.
using System.Collections.Generic; using System.Linq; using WebApiRepositoryPatternDemo.Core.Entities; using WebApiRepositoryPatternDemo.Core.Interfaces; namespace WebApiRepositoryPatternDemo.Infrastructure.Repository { public class CityRepository : ICityRepository { CityDataContext context = new CityDataContext(); public void Add(Core.Entities.City b) { context.Cities.Add(b); context.SaveChanges(); } public void Edit(Core.Entities.City b) { context.Entry(b).State = System.Data.Entity.EntityState.Modified; } public void Remove(string Id) { City b = context.Cities.Find(Id); context.Cities.Remove(b); context.SaveChanges(); } public IEnumerable<Core.Entities.City> GetCity() { return context.Cities; } public Core.Entities.City FindById(int Id) { var c = (from r in context.Cities where r.Id == Id select r).FirstOrDefault(); return c; } } }
CityRepository 클래스의 구현은 매우 간단합니다. 일반적인 LINQ to Entity 코드를 사용하여 CRUD 작업을 수행하는 것을 볼 수 있습니다. 모든 클래스를 구현한 후 인프라 프로젝트는 아래 이미지와 같아야 합니다.

Create the WebAPI project
이제 Web API 프로젝트를 만들어 보겠습니다. 시작하려면 다음 참조를 추가해야 합니다.
- 핵심 프로젝트의 참조
- 인프라 프로젝트의 참고 자료
- Entity 프레임워크에 대한 참조
Web API 프로젝트에 모든 참조를 추가한 후 APP에서 연결 문자열(이전 단계 cityconnectionstring에서 추가됨)을 복사합니다. 인프라 프로젝트를 Web API 프로젝트의 web.config에 구성합니다. 그런 다음 Global.asax 파일을 열고 Application_Start() 메서드에서 아래 코드 줄을 추가하여 시드 데이터가 데이터베이스에 삽입되었는지 확인합니다.
CityDbInitalize db = new CityDbInitalize(); System.Data.Entity.Database.SetInitializer(db);
이 시점에서 Web API 프로젝트를 빌드한 다음 Controllers 폴더와 새 컨트롤러를 마우스 오른쪽 버튼으로 클릭합니다. 아래 이미지와 같이 Entity Framework 옵션을 사용하여 작업이 있는 Web API 2 컨트롤러를 선택하고 스캐폴딩을 사용하여 새 컨트롤러를 만듭니다.

다음으로, Controller를 추가하려면 City 클래스를 Model 클래스로, CityDataContext 클래스를 Data 컨텍스트 클래스로 선택합니다.

추가를 클릭하면 Controllers 폴더에 CitiesController라는 이름의 Web API 컨트롤러가 생성되었음을 알 수 있습니다. 이 시점에서 웹 API를 실행하면 아래 이미지와 같이 브라우저에서 도시를 GET 할 수 있습니다.

여기서는 Entity Framework CodeFirst 접근 방식과 리포지토리 패턴을 사용하여 웹 API를 만들었습니다. api/cities URL에서 POST, GET, PUT 및 DELETE 작업을 수행하여 CRUD 작업을 수행할 수 있습니다.
JQuery Client to consume Web API
이제 igChart에 도시의 인구를 표시해 보겠습니다. 아래 목록과 같이 HTML에 IgniteUI JS 및 CSS 파일의 참조를 추가했습니다.
<title>igGrid CRUD Demo</title> <link href="Content/Infragistics/css/themes/infragistics/infragistics.theme.css" rel="stylesheet" /> <link href="Content/Infragistics/css/structure/infragistics.css" rel="stylesheet" /> <link href="Content/bootstrap.min.css" rel="stylesheet" /> <script src="Scripts/modernizr-2.7.2.js"></script> <script src="Scripts/jquery-2.0.3.js"></script> <script src="Scripts/jquery-ui-1.10.3.js"></script> <script src="Scripts/Infragistics/js/infragistics.core.js"></script> <script src="Scripts/Infragistics/js/infragistics.dv.js"></script> <script src="Scripts/Infragistics/js/infragistics.lob.js"></script> <script src="Scripts/demo.js"></script>
Body 요소에서 아래 목록과 같이 테이블로 추가했습니다.
<table> <tr> <td id="columnChart" class="chartElement"></td> <td id="columnLegend" style="float: left"></td> </tr> </table>
jQuery의 document ready 함수에서 테이블을 igChart로 변환하려면 아래 목록과 같이 테이블을 선택하고 igChart로 변환해야 합니다.
$("#columnChart").igDataChart({ width: "98%", height: "350px", dataSource: "http://localhost:56649/api/Cities", legend: { element: "columnLegend" }, title: "Cities Population", subtitle: "Population of Indian cities", axes: [{ name: "xAxis", type: "categoryX", label: "Name", labelTopMargin: 5 }, { name: "yAxis", type: "numericY", title: "in Millions", }], series: [{ name: "series1", title: "2001", type: "column", isHighlightingEnabled: true, isTransitionInEnabled: true, xAxis: "xAxis", yAxis: "yAxis", valueMemberPath: "Population01" }, { name: "series2", title: "2005", type: "column", isHighlightingEnabled: true, isTransitionInEnabled: true, xAxis: "xAxis", yAxis: "yAxis", valueMemberPath: "Population05" }, { name: "series3", title: "2010", type: "column", isHighlightingEnabled: true, isTransitionInEnabled: true, xAxis: "xAxis", yAxis: "yAxis", valueMemberPath: "Population10" }, { name: "series4", title: "2015", type: "column", isHighlightingEnabled: true, isTransitionInEnabled: true, xAxis: "xAxis", yAxis: "yAxis", valueMemberPath: "Population15" }] });
여기서는 차트를 만들기 위해 다음 속성을 설정합니다.
- 데이터 소스 속성은 HTTP GET 작업에서 모든 도시 정보를 가져오기 위해 API/Cities로 설정됩니다
- 차트의 범례를 열 범례로 사용합니다.
- 차트의 높이와 너비
- 차트의 제목과 하위 제목입니다
- 차트의 XAxis 및 YAxis
- 또한 다음 속성을 설정하여 시리즈를 만들었습니다.
- 이름
- 제목
- 유형
- valueMemberPath – City 엔터티의 숫자 열 이름으로 설정해야 합니다.
응용 프로그램을 실행하면 웹 API의 도시 데이터가 아래 이미지와 같이 차트에 렌더링 된 것으로 표시됩니다.

결론
여기 있습니다! 이 게시물에서는 리포지토리 패턴 및 Entity Framework 코드 우선 접근 방식을 사용하여 ASP.NET Web API를 만드는 방법을 배웠습니다. 이 게시물이 도움이 되었기를 바라며 읽어 주셔서 감사합니다!
