카테고리 없음

[.Net] EF Core 프로젝트 세팅 및 테이블 생성하기

포그너 2023. 7. 26. 10:31

M1 mac 에서 MS SQL Server설치 for Docker 및 접속 방법은 아래 링크를 확인해주세요

https://digitaldetox.tistory.com/entry/M1-Mac에-SQL-Server를-설치하는-방법FeatDocker

.NET Core MVC 프로젝트 생성

https://digitaldetox.tistory.com/entry/M1-mac-NET-Core-MVC-프로젝트-시작

 

Entity Framework Core 기본 사용법

Entity Framework Core를 사용하여 .NET Core 콘솔 애플리케이션에서 SQL Server와 연결하고 데이터베이스를 생성하며, 마이그레이션을 적용하여 테이블을 만드는 방법을 알아보겠습니다.

 

프로젝트 세팅

EF Core 패키지 추가하기

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design

 

데이터베이스 연결 설정

appsettings.json 파일에 데이터베이스 연결 정보를 작성해야 합니다. 다음과 같이 작성합니다.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost,1433;Database=YourDatabaseName;User=YourUsername;Password=YourPassword"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

SQL Server 연결 중 Authentication 에러 …

Trust 해주거나 connection string TrustServerCertificate=True; 추가

 

Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 35 - An internal exception was caught)
---> 
System.Security.Authentication.AuthenticationException: The remote certificate was rejected by the provided RemoteCertificateValidationCallback.
at System.Net.Security.SslStream.SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception)
at System.Net.Security.SslStream.CompleteHandshake(SslAuthenticationOptions sslAuthenticationOptions)

 

DBContext 설정

Program.cs 파일에서 DBContext를 설정합니다.

using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;


var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json");


var configuration = builder.Build();
var connectionString = configuration.GetConnectionString("DefaultConnection");


builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

Razor Web app 프로젝트일 경우에는 아래와 같이 만듭니다.

// .NET Web app project
var builder = WebApplication.CreateBuilder(args);


// Add services to the container.
builder.Services.AddRazorPages();


var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");


builder.Services.AddDbContext<ApplicationDbContext>(options => 
    options.UseSqlServer(connectionString));


var app = builder.Build();

ApplicationDbContext class 를 생성합니다.

using Microsoft.EntityFrameworkCore;


public class ApplicationDbContext : DbContext
{
	public ApplicationDbContext(){
    }
    
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {   
    }
	
    // 원하는 테이블 생성
	public DbSet<UserModel> User { get; set; }
}

 

Migration 스크립트 생성

EF Core를 사용하여 데이터베이스에 테이블을 생성하기 위해 migration 스크립트를 만듭니다.

dotnet ef migrations add create_tables

Migration 롤백

필요한 경우 migration을 롤백할 수도 있습니다.

dotnet ef migrations remove

Migration 적용

생성된 migration 스크립트를 실제 데이터베이스에 적용합니다.

dotnet ef database update

위 명령을 실행하면 데이터베이스에 테이블이 생성됩니다.

마무리

이제 EF Core를 사용하여 SQL Server와 연결하고 데이터베이스를 생성하며, 마이그레이션을 적용하여 테이블을 만드는 방법을 알게 되었습니다. 데이터베이스를 쉽게 관리하고 변경을 추적하기 위해 EF Core를 사용하는 것이 좋습니다.

dotnet run 시 dev-certs 확인

반응형