.NET Core 6 Web API에서 Entity Framework Core 및 저장 프로시저를 사용한 CRUD 작업

이 기사에서는 엔티티 프레임워크 코어와 저장 프로시저를 사용하여 Web API를 구현하는 방법에 대해 설명합니다.

의제


  • .NET Core 6 웹 API 구현
  • 저장 프로시저 구현

  • 전제 조건


  • .NET 코어 SDK 6
  • SQL 서버
  • 비주얼 스튜디오 2022

  • .NET Core 6 웹 API 구현



    1 단계
    새 .NET Core 웹 API 애플리케이션 만들기


    2 단계
    애플리케이션 구성


    3단계
    추가 정보 제공


    4단계
    프로젝트 구조


    5단계
    Entities 폴더 안에 Product 클래스 생성

    using System.ComponentModel.DataAnnotations;
    
    namespace EntityFrameworkSP_Demo.Entities
    {
        public class Product
        {
            public int ProductId { get; set; }
            public string ProductName { get; set; }
            public string ProductDescription { get; set; }
            public int ProductPrice { get; set; }
            public int ProductStock { get; set; }
        }
    }
    


    6단계
    다음으로 Data 폴더 안에 새 DbContextClass를 추가합니다.

    using EntityFrameworkSP_Demo.Entities;
    using Microsoft.EntityFrameworkCore;
    
    namespace EntityFrameworkSP_Demo.Data
    {
        public class DbContextClass : DbContext
        {
            protected readonly IConfiguration Configuration;
    
            public DbContextClass(IConfiguration configuration)
            {
                Configuration = configuration;
            }
            protected override void OnConfiguring(DbContextOptionsBuilder options)
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            }
    
            public DbSet<Product> Product { get; set; }
        }
    }
    


    7단계
    나중에 Repositories 폴더 안에 IProductService 및 ProductService를 생성합니다.

    I제품 서비스

    using EntityFrameworkSP_Demo.Entities;
    
    namespace EntityFrameworkSP_Demo.Repositories
    {
        public interface IProductService
        {
            public Task<List<Product>> GetProductListAsync();
            public Task<IEnumerable<Product>> GetProductByIdAsync(int Id);
            public Task<int> AddProductAsync(Product product);
            public Task<int> UpdateProductAsync(Product product);
            public Task<int> DeleteProductAsync(int Id);
        }
    }
    


    제품서비스

    using EntityFrameworkSP_Demo.Data;
    using EntityFrameworkSP_Demo.Entities;
    using Microsoft.Data.SqlClient;
    using Microsoft.EntityFrameworkCore;
    
    namespace EntityFrameworkSP_Demo.Repositories
    {
        public class ProductService : IProductService
        {
            private readonly DbContextClass _dbContext;
    
            public ProductService(DbContextClass dbContext)
            {
                _dbContext = dbContext;
            }
    
            public async Task<List<Product>> GetProductListAsync()
            {
                return await _dbContext.Product
                    .FromSqlRaw<Product>("GetPrductList")
                    .ToListAsync();
            }
    
            public async Task<IEnumerable<Product>> GetProductByIdAsync(int ProductId)
            {
                var param = new SqlParameter("@ProductId", ProductId);
    
                var productDetails = await Task.Run(() => _dbContext.Product
                                .FromSqlRaw(@"exec GetPrductByID @ProductId", param).ToListAsync());
    
                return productDetails;
            }
    
            public async Task<int> AddProductAsync(Product product)
            {
                var parameter = new List<SqlParameter>();
                parameter.Add(new SqlParameter("@ProductName", product.ProductName));
                parameter.Add(new SqlParameter("@ProductDescription", product.ProductDescription));
                parameter.Add(new SqlParameter("@ProductPrice", product.ProductPrice));
                parameter.Add(new SqlParameter("@ProductStock", product.ProductStock));
    
                var result = await Task.Run(() =>  _dbContext.Database
               .ExecuteSqlRawAsync(@"exec AddNewProduct @ProductName, @ProductDescription, @ProductPrice, @ProductStock", parameter.ToArray()));
    
                return result;
            }
    
            public async Task<int> UpdateProductAsync(Product product)
            {
                var parameter = new List<SqlParameter>();
                parameter.Add(new SqlParameter("@ProductId", product.ProductId));
                parameter.Add(new SqlParameter("@ProductName", product.ProductName));
                parameter.Add(new SqlParameter("@ProductDescription", product.ProductDescription));
                parameter.Add(new SqlParameter("@ProductPrice", product.ProductPrice));
                parameter.Add(new SqlParameter("@ProductStock", product.ProductStock));
    
                var result = await Task.Run(() => _dbContext.Database
                .ExecuteSqlRawAsync(@"exec UpdateProduct @ProductId, @ProductName, @ProductDescription, @ProductPrice, @ProductStock", parameter.ToArray()));
                return result;
            }
            public async Task<int> DeleteProductAsync(int ProductId)
            {
                return await Task.Run(() => _dbContext.Database.ExecuteSqlInterpolatedAsync($"DeletePrductByID {ProductId}"));
            }
        }
    }
    


    FromSqlRaw 메서드는 데이터베이스에 대해 SQL 명령을 실행하는 데 사용되며 DbSet의 인스턴스를 반환합니다.
    ExecuteSqlRawAsync는 SQL 명령을 실행하는 데 사용되며 영향을 받는 행 수를 반환합니다.
    ExecuteSqlInterpolatedAsync는 SQL 명령을 실행하고 영향을 받는 행 수를 반환합니다.

    8단계
    appsettings.json 파일 내에 데이터베이스 연결 문자열 추가

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*",
      "ConnectionStrings": {
        "DefaultConnection": "Data Source=DESKTOP;Initial Catalog=StoredProcedureEFDemo;User Id=sa;Password=database;"
      }
    }
    


    9단계
    Program 클래스 내부에 서비스 등록

    using EntityFrameworkSP_Demo.Data;
    using EntityFrameworkSP_Demo.Repositories;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddScoped<IProductService, ProductService>();
    builder.Services.AddDbContext<DbContextClass>();
    
    builder.Services.AddControllers();
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    
    app.UseAuthorization();
    
    app.MapControllers();
    
    app.Run();
    


    10단계

    다음으로 새 제품 컨트롤러를 만듭니다.

    using EntityFrameworkSP_Demo.Entities;
    using EntityFrameworkSP_Demo.Repositories;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using System.Collections.Generic;
    
    namespace EntityFrameworkSP_Demo.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class ProductsController : ControllerBase
        {
            private readonly IProductService productService;
    
            public ProductsController(IProductService productService)
            {
                this.productService = productService;
            }
    
            [HttpGet("getproductlist")]
            public async Task<List<Product>> GetProductListAsync()
            {
                try
                {
                    return await productService.GetProductListAsync();
                }
                catch
                {
                    throw;
                }
            }
    
            [HttpGet("getproductbyid")]
            public async Task<IEnumerable<Product>> GetProductByIdAsync(int Id)
            {
                try
                {
                    var response = await productService.GetProductByIdAsync(Id);
    
                    if(response == null)
                    {
                        return null;
                    }
    
                    return response;
                }
                catch
                {
                    throw;
                }
            }
    
            [HttpPost("addproduct")]
            public async Task<IActionResult> AddProductAsync(Product product)
            {
                if(product == null)
                {
                    return BadRequest();
                }
    
                try
                {
                    var response = await productService.AddProductAsync(product);
    
                    return Ok(response);
                }
                catch
                {
                    throw;
                }
            }
    
            [HttpPut("updateproduct")]
            public async Task<IActionResult> UpdateProductAsync(Product product)
            {
                if (product == null)
                {
                    return BadRequest();
                }
    
                try
                {
                    var result =  await productService.UpdateProductAsync(product);
                    return Ok(result);
                }
                catch
                {
                    throw;
                }
            }
    
            [HttpDelete("deleteproduct")]
            public async Task<int> DeleteProductAsync(int Id)
            {
                try
                {
                    var response = await productService.DeleteProductAsync(Id);
                    return response;
                }
                catch
                {
                    throw;
                }
            }
        }
    }
    


    11단계
    패키지 관리자 콘솔에서 다음 명령을 실행하여 마이그레이션을 생성하고 데이터베이스를 업데이트합니다.

    추가 마이그레이션 "초기"
    업데이트 데이터베이스

    12단계
    저장 프로시저의 구현

    GetPrductList

    USE [StoredProcedureEFDemo]
    GO
    
    /****** Object:  StoredProcedure [dbo].[GetPrductList]    Script Date: 10/16/2022 11:08:29 AM ******/
    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    CREATE OR ALTER PROCEDURE [dbo].[GetPrductList]
    AS
    BEGIN
        SELECT * FROM dbo.Product
    END
    GO
    


    GetPrductByID

    USE [StoredProcedureEFDemo]
    GO
    
    /****** Object:  StoredProcedure [dbo].[GetPrductByID]    Script Date: 10/16/2022 11:09:04 AM ******/
    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    CREATE OR ALTER PROCEDURE [dbo].[GetPrductByID]
    @ProductId int
    AS
    BEGIN
        SELECT
            ProductId,
            ProductName,
            ProductDescription,
            ProductPrice,
            ProductStock
        FROM dbo.Product where ProductId = @ProductId
    END
    GO
    


    새 제품 추가

    USE [StoredProcedureEFDemo]
    GO
    
    /****** Object:  StoredProcedure [dbo].[AddNewProduct]    Script Date: 10/16/2022 11:09:20 AM ******/
    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    
    CREATE OR ALTER PROCEDURE [dbo].[AddNewProduct]
    @ProductName [nvarchar](max),
    @ProductDescription [nvarchar](max),
    @ProductPrice int,
    @ProductStock int
    AS
    BEGIN
        INSERT INTO dbo.Product
            (
                ProductName,
                ProductDescription,
                ProductPrice,
                ProductStock
            )
        VALUES
            (
                @ProductName,
                @ProductDescription,
                @ProductPrice,
                @ProductStock
            )
    END
    GO
    
    


    제품 업데이트

    USE [StoredProcedureEFDemo]
    GO
    
    /****** Object:  StoredProcedure [dbo].[UpdateProduct]    Script Date: 10/16/2022 11:09:38 AM ******/
    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    
    CREATE OR ALTER PROCEDURE [dbo].[UpdateProduct]
    @ProductId int,
    @ProductName [nvarchar](max),
    @ProductDescription [nvarchar](max),
    @ProductPrice int,
    @ProductStock int
    AS
    BEGIN
        UPDATE dbo.Product
        SET
            ProductName = @ProductName,
            ProductDescription = @ProductDescription,
            ProductPrice = @ProductPrice,
            ProductStock = @ProductStock
        WHERE ProductId = @ProductId
    END
    GO
    


    DeletePrductByID

    USE [StoredProcedureEFDemo]
    GO
    
    /****** Object:  StoredProcedure [dbo].[DeletePrductByID]    Script Date: 10/16/2022 11:09:50 AM ******/
    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    CREATE OR ALTER PROCEDURE [dbo].[DeletePrductByID]
    @ProductId int
    AS
    BEGIN
        DELETE FROM dbo.Product where ProductId = @ProductId
    END
    GO
    


    13단계
    마지막으로 응용 프로그램을 실행하십시오.



    http://localhost:5002/api/Products/getproductlist



    http://localhost:5002/api/Products/getproductbyid?Id=16



    http://localhost:5002/api/Products/addproduct



    http://localhost:5002/api/Products/updateproduct



    http://localhost:5002/api/Products/deleteproduct?Id=19



    깃허브 URL



    https://github.com/Jaydeep-007/EntityFrameworkSP_Demo.git

    결론



    여기서는 Entity Framework Core 및 저장 프로시저를 사용한 웹 API 구현에 대해 논의했습니다.

    행복한 학습!

    좋은 웹페이지 즐겨찾기