asp.net webapi와 sqlite를 이용하여 Customer 모델 CRUD 하기

이번에는 이전 게시물에서 만든 TestApi를 이용하여 Customer를 CRUD 해보도록하겠습니다.

출처 : https://www.udemy.com/course/build-an-app-with-aspnet-core-and-angular-from-scratch/?couponCode=ST3MT72524

소스는 github에서 받을 수 있습니다.
https://github.com/tigersarang/BasicAspnetWebapi.git

1. Customer 모델 생성
  1) Models 폴더를 생성하고 Customer.cs 파일을 생성합니다.

namespace TestApi.Models
{
    public class Customer
    {
        public int Id { get; set; }
        public string? Name { get; set; }
    }
}


2. 데이터베이스 연결 문자열 생성 및 DbContext 생성
  1) appsettings.Development.json 을 다음과 같이 수정합니다.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection" : "Data Source = TestApiDb.db"
  }
}


  2) 터미널 탭에 있는 nuget탭을 선택하고 다음 패키지를 설치합니다.
    - Microsoft.EntityFrameworkCore.Design @Microsoft
    - 
Microsoft.EntityFrameworkCore.Sqlite @Microsoft


  3) Data 폴더를 생성 후 DataContext.cs 파일을 생성합니다.

using Microsoft.EntityFrameworkCore;
using TestApi.Models;

namespace TestApi.Data
{
    public class DataContext(DbContextOptions options) : DbContext(options)
    {
        public DbSet<Customer> Customers { get; set; }
    }
}

  4) Program.cs 파일을 수정합니다.

builder.Services.AddControllers();
builder.Services.AddDbContext<DataContext>(options => {
    options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
});

3. sqlite 데이터베이스 생성 및 테이블 생성
  1) 터미널에서 다음 명령어를 실행합니다.
    - dotnet ef migrations add init -o Data/Migrations 를 실행
    - dotnet ef database update 를 실행
  2) Vs Code 바탕화면에 있는 단축키인 Show All Commands를 실행한 후 검색어로 sqlite를 입력하면 Open Database가
      보일 겁니다. 그걸 클릭합니다.

      
    그러면 왼쪽하단에 Sqlite explorer가 보일겁니다. 그러면 테이블 생성은 잘 된겁니다.

      

4. Repository, Controller 생성 및 DI 적용하기
  1) Repository 생성하기
    - Repository 폴더를 생성 후 ICustomerRepository.cs 파일을 생성하고 다음과 같이 입력합니다.

using TestApi.Models;

namespace TestApi.Repositories
{
    public interface ICustomerRepository
    {
        Task<IEnumerable<Customer>> GetCustomers();
        Task<Customer?> GetCustomer(int id);
        Task<Customer> AddCustomer(Customer customer);
        Task<Customer> UpdateCustomer(Customer customer);
    }
}

    - CustomerRepository.cs 파일을 생성하고 다음과 같이 입력합니다.
    - 

  1) Controller 폴더에서 BaseApiController.cs 파일을 추가하고 내용을 다음과 같이 입력합니다.

using Microsoft.AspNetCore.Mvc;

namespace TestApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class BaseApiController : ControllerBase
    {
       
    }
}


  2) Services 폴더를 생성하고 CustomerService.cs 파일을 추가하고 내용을 다음과 같이 입력합니다.

using Microsoft.EntityFrameworkCore;
using TestApi.Data;
using TestApi.Models;
using TestApi.Repositories;

namespace TestApi.Services
{
    public class CustomerService : ICustomerRepository
    {
        private readonly DataContext _dataContext;

        public CustomerService(DataContext dataContext)
        {
            this._dataContext = dataContext;
        }
        public async Task<Customer> AddCustomer(Customer customer)
        {
            await _dataContext.AddAsync(customer);
            await _dataContext.SaveChangesAsync();
            return customer;
        }

        public async Task<Customer?> GetCustomer(int id)
        {
            return await _dataContext.Customers.SingleOrDefaultAsync(x => x.Id == id);
        }

        public async Task<IEnumerable<Customer>> GetCustomers()
        {
            return await _dataContext.Customers.ToListAsync();
        }

        public async Task<Customer> UpdateCustomer(Customer customer)
        {
            _dataContext.Customers.Attach(customer);
            _dataContext.Entry(customer).State = EntityState.Modified;
            await _dataContext.SaveChangesAsync();
            return customer;
        }
    }
}

  3) CustomerService를 DI하기 위해  program.cs를 다음과 같이 수정합니다.

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<ICustomerRepository, CustomerService>();

  3) Controller 폴더에서 CustomerApiController.cs 파일을 추가하고 내용을 다음과 같이 입력합니다.

using Microsoft.AspNetCore.Mvc;
using TestApi.Models;
using TestApi.Repositories;

namespace TestApi.Controllers
{
    public class CustomerApiController : BaseApiController
    {
        private readonly ICustomerRepository _customerRepository;

        public CustomerApiController(ICustomerRepository customerRepository)
        {
            this._customerRepository = customerRepository;
        }
        [HttpGet]
        public async Task<IActionResult> GetCustomersAsync() {
            return Ok(await _customerRepository.GetCustomers());
        }

        [HttpGet("{id}")]
        public async Task<IActionResult> GetCustomerAsync(int id){
            return Ok( await _customerRepository.GetCustomer(id));
        }

        [HttpPost]
        public async Task<IActionResult> AddCustomerAsync(Customer customer) {
            return Ok(await _customerRepository.AddCustomer(customer));
        }

        [HttpPut]
        public async Task<IActionResult> UpdateCustomerAsync(Customer customer) {
            return Ok(await _customerRepository.UpdateCustomer(customer));
        }
    }
}

  4) 터미널에서 dotnet run 을 실행하여 프로그램을 실행합니다. 그러면 터미널에 어느 포트로 실행되고 있는지 알 수 있습니다.

    

  5) 테스트를 위해 swagger에 접속합니다.
      http://localhost:5172/swagger/index.html 로 접속을해서 잘되는지 테스트를 합니다.




            

댓글 쓰기

댓글 목록