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
반응형
'Entity Framework Core' 카테고리의 다른 글
ASP.NET Core] Entity Framework Core - Migrations (0) | 2023.05.24 |
---|---|
ASP.NET Core] Entity Framework Core - database model 구성방법 (0) | 2023.05.23 |
ASP.NET Core] Entity Framework Core란? (1) | 2023.05.23 |
ASP.NET Core] Entity Framework Core - SQL Queries (0) | 2023.05.09 |
ASP.NET Core] Entity Framework Core - 1. MSSQL DB 연동 (0) | 2021.12.24 |
댓글