본문 바로가기
GraphQL(HotChocolate)

.NET 6] Hot Chocolate GraphQL : EF Core (3)

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

DbContext를 사용하도록 Query class를 수정하자. 

    public class Query
    {
        //public Book GetBook() =>
        //    new Book
        //    {
        //        Title = "C# in depth.",
        //        Author = new Author
        //        {
        //            Name = "Jon Skeet"
        //        }
        //    };


        public IQueryable<Book> GetBooks([Service] ApplicationDbContext context)
            => context.Books;

    }

ApplicationDbContext.cs

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

        }

        public DbSet<Category> Categories { get; set; }
        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);
        }
    }

Book.cs

    //public class Book
    //{
    //    public string Title { get; set; }

    //    public Author Author { get; set; }
    //}

    //public class Author
    //{
    //    public string Name { get; set; }
    //}

    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; }
    }

Author가 조회되지 않는다. 

Author를 조회하기 위해 package를 추가 설치한다. 

Install-Package HotChocolate.Data.EntityFramework -Version 12.6.0

Program.cs 

builder.Services
    .AddGraphQLServer()
    .AddQueryType<Query>()
    .AddProjections()
    .AddFiltering()
    .AddSorting();

Query.cs

    public class Query
    {
        [UseProjection]
        [UseFiltering]
        [UseSorting]
        public IQueryable<Book> GetBooks([Service] ApplicationDbContext context)
            => context.Books;

    }

Author가 조회됨을 확인할 수 있다. 

Window Command Prompt에서 EF Core 쿼리 로그를 확인할 수 있다. 

info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (21ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT [b].[Title], CAST(1 AS bit), [a].[Name]
      FROM [Books] AS [b]
      INNER JOIN [Authors] AS [a] ON [b].[AuthorId] = [a].[AuthorId]

 

728x90
반응형

댓글