본문 바로가기
GraphQL(HotChocolate)

.NET 6] Hot Chocolate GraphQL : mutation(5)

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

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



    public record AddAuthorInput(string Name = "");
    public record AddAuthorPayload(Author author);

Mutation.cs

        [UseDbContext(typeof(ApplicationDbContext))]
        public async Task<AddAuthorPayload> AddAuthroAsync(AddAuthorInput input, [ScopedService] ApplicationDbContext context)
        {
            var author = new Author
            {
                Name = input.Name
            };

            context.Authors.Add(author);
            await context.SaveChangesAsync();

            return new AddAuthorPayload(author);

        }

Program.cs

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

728x90
반응형

댓글