Skip to content

Latest commit

 

History

History
83 lines (67 loc) · 2.46 KB

File metadata and controls

83 lines (67 loc) · 2.46 KB

DB 연동

VSCode 환경 셋팅

  1. SQL Server Extension을 설치

  2. SQL Sever 다운로드

  3. SSMS 다운로드

  4. Connection String 설정

    Untitled

    Untitled

AppDbContext 및 DataModel구성

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Server.Data;

namespace Server.DB
{
    public class AppDbContext : DbContext
    {
        public DbSet<AccountDb> Accounts { get; set; }
        public DbSet<PlayerDb> Players { get; set; }

        static readonly ILoggerFactory _logger = LoggerFactory.Create(builder => { builder.AddConsole(); });

        string _connectionString = @"Server=localhost;Database=GameDB;Trusted_Connection=True;";
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            options
                .UseLoggerFactory(_logger)
                .UseSqlServer(ConfigManager.Config == null ? _connectionString : ConfigManager.Config.connectionString);
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            // AccountName에 인덱스를 걸어줌
            // IsUnique =>  AccountName에 중복된 데이터가 들어어지 못하도록 방지
            builder.Entity<AccountDb>()
                .HasIndex(a => a.AccountName)
                .IsUnique();
            builder.Entity<PlayerDb>()
                .HasIndex(p => p.PlayerName)
                .IsUnique();
        }
    }
}
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

namespace Server.DB
{
    [Table("Account")]
    public class AccountDb
    {
        public int AccountDbId { get; set; }
        public string AccountName { get; set; }
        public ICollection<PlayerDb> Players { get; set; }
    }

    [Table("Player")]
    public class PlayerDb
    {
        public int PlayerDbId { get; set; }
        public string PlayerName { get; set; }
        public AccountDb Account { get; set; } 
    }
}

Migration 셋팅

  1. 툴설치 ⇒ dotnet tool install --global dotnet-ef
  2. DbContext 소스가 있는 프로젝트로 폴더 이동 ⇒ cd
  3. dotnet ef migrations add ⇒ Migration 등록
  4. dotnet ef database update ⇒ 해당 Migration을 DB에 반영