본문 바로가기
Entity Framework Core

ASP.NET Core] Entity Framework Core - 2. One To Many

by Fastlane 2022. 2. 8.
728x90
반응형

Nuget Package 설치 :

  • Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore.Tools : DB Migration에 필요함

 

아래 관계(One To Many)의 테이블과 매핑할 Entity Framework model class를 생성해보자. 

Book.cs

    public class Author
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int AuthorId { get; set; }
        [Required]
        public string Name { get; set; }
        public ICollection<Book> Books { get; set; }
    }

    public class Book
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int BookId { get; set; }
        [Required]
        public int AuthorId { get; set; }
        [Required]
        public string Title { get; set; }
        public virtual Author? Author { get; set; }
    }

ApplicationDbContext.cs

    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {

        }

        public DbSet<Author> Authors { get; set; }
        public DbSet<Book> Books { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Author>()
                .HasMany(a => a.Books)
                .WithOne();


            modelBuilder.Entity<Book>()
                .HasOne(b => b.Author)
                .WithMany(a => a.Books)
                .HasForeignKey(b => b.AuthorId);
        }
    }

패키지 관리자 콘솔

PM> Add-Migration
PM> Update-Database

DB에 아래와 같이 테이블이 자동 생성됨을 확인할 수 있다. 

 

728x90
반응형

댓글