본문 바로가기

DB

mysql, heroku, c# 연동

  1. nuget 패키지 관리자에서 mysql을 검색하여 Prmelo.EntityFrameworkCore.MySql을 다운로드 받는다.
  2.  appsettings.json에 헤로쿠 디비 연결정보 작성

3. 모델 생성

//Models.Book.cs

using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace BookStore.Models
{
    public class Book
    {
    	[Display(Name = "Book Id")]
        public long BookId { get; set; }

		[Display(Name = "Book Name")]
        public string BookName { get; set; }
        
        public string Author { get; set; }
		
        [Display(Name = "Date of Publish")]
        public DateTime DateOfPublish { get; set; } 

        public int Rate { get; set; } //평점

       	public string Review { get; set; } 

    }

    //테이블 생성 메소드
    public class BookConfiguration : IEntityTypeConfiguration<Book>
    {
        public void Configure(EntityTypeBuilder<PBook> builder)
        {
            builder.ToTable("Book");
            builder.HasKey(x => x.BookId); //PK
            builder.Property(x => x.BookName).IsRequired(); //IsRequired()는 필수 컬럼
            builder.Property(x => x.Author).IsRequired();
            builder.Property(x => x.DateOfPublish).IsRequired();
            builder.Property(x => x.Rate);
            builder.Property(x => x.Review).IsRequired();

        }
    }
    
    

}

4. DB Context 작성

//Data.BookStore.cs

using System;
using LifeManage.Models;
using Microsoft.EntityFrameworkCore;

namespace BookStore.Data
{
    public class BookStoreContext: DbContext
    {
        
        public BookStoreContext(DbContextOptions<BookStoreContext> options) : base(options) { }
       

        public DbSet<Book> Books { get; set; } //모델이름 복수형으로 작성

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(new BookConfiguration());
        }


    }

    
}

5. 닷넷 ef를 사용하여 데이터베이스에 마이그레이션
프로젝트를 터미널에서 열고 입력한다.

dotnet ef migration add add_book_table
dotnet ef database update

'DB' 카테고리의 다른 글

자주쓰는 SQL Server 기능 모음  (0) 2025.01.02
Java Script Mongoose 비동기 처리  (0) 2023.12.29
sql join  (1) 2023.09.15
aws 리눅스 마리아 db 설치  (1) 2023.09.11
마리아 DB 외부접속(구글 클라우드 플랫폼 VM)  (0) 2022.11.22