[ASP.NET Core + PostgreSQL] ASP.NET EF Core + PostgreSQL 환경에서 마이그레이션 생성하고 적용하기
ASP.NET EF Core + PostgreSQL 환경에서 마이그레이션 생성하고 적용하기
순서 요약
- DbContext와 모델 클래스 설정
- 마이그레이션 추가 및 업데이트
- 테이블이 정상적으로 생성되었는지 확인
1️⃣ AppDbContext 설정
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<User> Users { get; set; }
}
DbContext 클래스 생성 및 DbSet<> 등록
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasIndex(u => u.Email).IsUnique();
}
OnModelCreating 메서드에서 필요한 설정 추가할 수 있음 (꼭 안 해도 됨)
2️⃣ 모델 클래스 작성
using System;
using System.ComponentModel.DataAnnotations;
public class User
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Username { get; set; } = string.Empty;
[StringLength(100)]
public string? Email { get; set; }
[Required]
public string PasswordHash { get; set; } = string.Empty;
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
public DateTimeOffset? UpdatedAt { get; set; } = DateTimeOffset.UtcNow;
}
샘플로 'User' 모델 클래스를 만들어 보자.
3️⃣ 컨트롤러 작성
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
private readonly AppDbContext _context;
public UsersController(AppDbContext context)
{
_context = context;
}
[HttpGet]
public async Task<IActionResult> GetUsers()
{
var users = await _context.Users.ToListAsync();
return Ok(users);
}
}
마이그레이션 적용에 필수는 아니지만 API 연동 시 필요한 컨트롤러도 작성해두자.
4️⃣ 마이그레이션 추가 및 업데이트
dotnet ef migrations add InitialCreate
마이그레이션 파일 생성
dotnet ef database update
마이그레이션 적용 (데이터베이스 업데이트)
5️⃣ 테이블 생성 확인
- psql에서 \dt 명령어 실행하여 테이블 목록 확인
- 특정 테이블 스키마 확인하는 \dt; 등의 명령어 소개
psql -U userName -d DBName
psql 열기
\dt;
전체 테이블 조회해서 USERS 테이블 생겼는지 확인
에러 대응
[ASP.NET Core + PostgreSQL] 마이그레이션 업데이트 중 'timestamp with time zone' literal cannot be generated for Unspe
📌 문제 내용 DB 생성 > 마이그레이션 추가 > dotnet ef database update로 마이그레이션 업데이트이 과정 이후에 아래 에러가 반복적으로 발생했다.DateTime 타입을 저장할 때 명확한 시간대 정보(UTC 등)
j-lisa-dev.tistory.com
[ASP.NET Core + PostgreSQL] 마이그레이션 업데이트 중 The model for context 'AppDbContext' has pending changes. 에러
dotnet ef database update이 커맨드를 실행해서 마이그레이션을 데이터베이스에 적용하려고 할 때 아래 에러가 발생할 수 있다. 모델과 데이터베이스 스키마가 일치하지 않아서 발생하는 에러로, 모
j-lisa-dev.tistory.com