Entity Framework

1. Visual Studio에서 Blazor + Entity Framework 시작하기

샐님 2024. 1. 13. 11:20
728x90
반응형

1. Visual Studio 에서 .net 6 blazor server app 프로젝트 생성

2. 도구 > Nuget 패키지 관리자 > 솔루션용 Nuget 패키지 관리 에서 

Microsoft.EntityFrameworkCore 버전 6.026

Microsoft.EntityFrameworkCore.SqlServer 버전 6.026

을 설치.

3. Data 폴더에서 DemoDbContext.cs 파일 생성

DbContext 를 상속받는데, DbContext는 EntityFrameworkCore 의 클래스이다.

using Microsoft.EntityFrameworkCore;

namespace EntityFrameworkTest.Data
{
    public class DemoDbContext : DbContext
    {
    }
}

 

4.  DemoDbContext 타입의 옵션을 기본  클래스에 전달 *

using Microsoft.EntityFrameworkCore;

namespace EntityFrameworkTest.Data
{
    public class DemoDbContext : DbContext
    {
        public DemoDbContext(DbContextOptions<DemoDbContext> options) : base(options) // DemoDbContext 타입의 옵션을 기본  클래스에 전달할것이다.dbContext는 우리가 상속하는 것이므로 이를 전달하고 거기까지 가서 DbContext가 설정됩니다.
        {    
            
        }
    }
}

5. DbContext를 Service로 생성하기 위해 DbContextFactory 생성

- 종속성 주입 (Dependency Injection)을 사용하여 우리가 사용하는 모든 서비스에 dbContext 팩토리를 주입할 수 있음을 의미합니다. 

using EntityFrameworkTest.Data;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("Default")
    ?? throw new NullReferenceException("No connection string in config!");
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();

// 애플리케이션이 시작될 때 해당 서비스를 rpogram.cs의 서비스에 추가했기 때문에 
//해당 서비스를 생성하고 종속성 주입을 사용하여 해당 팩토리를 다른 클래스에 주입할 수 있다는 의미

builder.Services.AddDbContextFactory<DemoDbContext>((DbContextOptionsBuilder options)=> 
options.UseSqlServer(connectionString));
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

 

- ConnectionString 은 appsettings.json 파일에서 설정

{

  "ConnectionStrings": {
    "Default": "Data Source=(db스트링 입력)"
  },
   "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

 

6. 데이터베이스의 테이블인 DB Set 정의

 - Data 폴더 > Model 폴더생성 > Customer.cs (모델) 생성

using System.ComponentModel.DataAnnotations;

namespace EntityFrameworkTest.Data.Model
{
    public class Customer
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public DateTime CreateDate { get; set; }
    }
}

 

7. DemoDbContext.cs 에서 Db Set 설정

using EntityFrameworkTest.Data.Model;
using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography.X509Certificates;

namespace EntityFrameworkTest.Data
{
    public class DemoDbContext : DbContext
    {
        public DemoDbContext(DbContextOptions<DemoDbContext> options) : base(options) // DemoDbContext 타입의 옵션을 기본  클래스에 전달할것이다.. //dbContext는 우리가 상속하는 것이므로 이를 전달하고 거기까지 가서 DbContext가 설정됩니다.
        {
        }


        //데이터베이스의 테이블인 db set을 정의
        //테이블을 모델링하기 위해 일종의 모델이 필요한 db 세트 정의
        public DbSet<Customer> customers { get; set; }
    }
}

 

8. 마이그레이션 (dbset을 데이터베이스로) 

 - 마이그레이션은 변경 로그이다. 코드에서 변경한 내용을 이해하고 이를 통해 변환하는 방법. 스키마가 변경될때 마다 

  마이그레이션이라는 콘솔 명령을 사용.< add migration > Entity Framework 는 모든 변경사항을 git처럼 본다. 커밋을 수행하면 수행한 모든 변경사항을 보고 해당 변경 사항을 브랜치에 적용. 

customer 의 db set은 우리 context에 추가-> 데이터베이스에 새 테이블을 추가해야 함을 의미.

 마이그레이션을 수행할때 마이그레이션 이름 지정필요 

 

도구 > Nuget 패키지 관리자 > 패키지 콘솔 실행

 Add-Migraton "added_customer_table" 입력후 엔터

 

에러가 나면 command line 관리하는 패키지 설치 필요

Microsoft.EntityFrameworkCore.Tools 버전 6.0.26 

Add-Migraton "added_customer_table" 입력후 엔터

 

 

이작업을 수행하고 나면

Migration 폴더가 생성되고 cs 파일이 생성된 것을 확인

20240113021117_added_customer_table.cs

using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace EntityFrameworkTest.Migrations
{
    public partial class added_customer_table : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "customers",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    Age = table.Column<int>(type: "int", nullable: false),
                    CreateDate = table.Column<DateTime>(type: "datetime2", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_customers", x => x.Id);
                });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "customers");
        }
    }
}

 

데이터베이스에 생성될 테이블 내용

 

8. 데이터베이스에 실제로 적용

도구> Nuget 패키지 관리자 > 관리자 콘솔

update-database 라고 입력 후 엔터

데이터베이스에 customers 테이블이 추가된것을 확인

728x90
반응형