첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
본 블로그는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 블로그 콘텐츠 향상을 위해 쓰여집니다.

728x90
반응형
728x170

TestProject.zip
다운로드

▶ Models/TestModel.cs

namespace TestProject.Models
{
    /// <summary>
    /// 테스트 모델
    /// </summary>
    public class TestModel
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Property
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region ID - ID

        /// <summary>
        /// ID
        /// </summary>
        public long ID { get; set; }

        #endregion
        #region 제목 - Name

        /// <summary>
        /// 제목
        /// </summary>
        public string Name { get; set; }

        #endregion
    }
}

 

728x90

 

▶ Models/TestData.cs

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;

using TestProject.Data;

namespace TestProject.Models
{
    /// <summary>
    /// 테스트 데이터
    /// </summary>
    public static class TestData
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Public

        #region 초기화하기 - Initialize(serviceProvider)

        /// <summary>
        /// 초기화하기
        /// </summary>
        /// <param name="serviceProvider">서비스 제공자</param>
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using(var context = new DatabaseContext(serviceProvider.GetRequiredService<DbContextOptions<DatabaseContext>>()))
            {
                if(context.Test.Any())
                {
                    return;
                }

                context.Test.AddRange
                (
                    new TestModel { ID = 1, Name = "테스트 1" },
                    new TestModel { ID = 2, Name = "테스트 2" },
                    new TestModel { ID = 3, Name = "테스트 3" },
                    new TestModel { ID = 4, Name = "테스트 4" },
                    new TestModel { ID = 5, Name = "테스트 5" }
                );

                context.SaveChanges();
            }
        }

        #endregion
    }
}

 

300x250

 

▶ Data/DatabaseContext.cs

using Microsoft.EntityFrameworkCore;

using TestProject.Models;

namespace TestProject.Data
{
    /// <summary>
    /// 데이터베이스 컨텍스트
    /// </summary>
    public class DatabaseContext : DbContext
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Property
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 테스트 - Test

        /// <summary>
        /// 테스트
        /// </summary>
        public DbSet<TestModel> Test { get; set; }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - DatabaseContext(options)

        /// <summary>
        /// 생성자
        /// </summary>
        /// <param name="options">옵션</param>
        public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
        {
        }

        #endregion
    }
}

 

▶ Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using TestProject.Data;

namespace TestProject
{
    /// <summary>
    /// 시작
    /// </summary>
    public class Startup
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Property
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 구성 - Configuration

        /// <summary>
        /// 구성
        /// </summary>
        public IConfiguration Configuration { get; }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - Startup(configuration)

        /// <summary>
        /// 생성자
        /// </summary>
        /// <param name="configuration">구성</param>
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 서비스 컬렉션 구성하기 - ConfigureServices(services)

        /// <summary>
        /// 서비스 컬렉션 구성하기
        /// </summary>
        /// <param name="services">서비스 컬렉션</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DatabaseContext>(options => options.UseInMemoryDatabase("TestDB"));

            services.AddControllers();
        }

        #endregion
        #region 구성하기 - Configure(app, environment)

        /// <summary>
        /// 구성하기
        /// </summary>
        /// <param name="app">애플리케이션 빌더</param>
        /// <param name="environment">웹 호스트 환경</param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment environment)
        {
            if(environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints
            (
                endpointRouterBuilder =>
                {
                    endpointRouterBuilder.MapControllers();
                }
            );
        }

        #endregion
    }
}

 

▶ Program.cs

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;

using TestProject.Models;

namespace TestProject
{
    /// <summary>
    /// 프로그램
    /// </summary>
    public class Program
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Private

        #region 프로그램 시작하기 - Main(argumentArray)

        /// <summary>
        /// 프로그램 시작하기
        /// </summary>
        /// <param name="argumentArray">배열 인자</param>
        public static void Main(string[] argumentArray)
        {
            IHost host = CreateHostBuilder(argumentArray).Build();

            using(IServiceScope scope = host.Services.CreateScope())
            {
                IServiceProvider serviceProvider = scope.ServiceProvider;

                try
                {
                    TestData.Initialize(serviceProvider);
                }
                catch(Exception exception)
                {
                    ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>();

                    logger.LogError(exception, "데이터베이스에 데이터 추가시 에러가 발생했습니다.");
                }
            }

            host.Run();
        }

        #endregion
        #region 호스트 빌더 생성하기 - CreateHostBuilder(argumentArray)

        /// <summary>
        /// 호스트 빌더 생성하기
        /// </summary>
        /// <param name="argumentArray">인자 배열</param>
        /// <returns>호스트 빌더</returns>
        public static IHostBuilder CreateHostBuilder(string[] argumentArray) =>
            Host.CreateDefaultBuilder(argumentArray)
                .ConfigureWebHostDefaults
                (
                    builder =>
                    {
                        builder.UseStartup<Startup>();
                    }
                );

        #endregion
    }
}

 

▶ Controllers/TestController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;

using TestProject.Data;
using TestProject.Models;

namespace TestProject.Controllers
{
    /// <summary>
    /// 테스트 컨트롤러
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class TestController : Controller
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region Field

        /// <summary>
        /// 데이터베이스 컨텍스트
        /// </summary>
        private readonly DatabaseContext context;

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - TestController(context)

        /// <summary>
        /// 생성자
        /// </summary>
        /// <param name="context">컨텍스트</param>
        public TestController(DatabaseContext context)
        {
            this.context = context;
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 구하기 - Get() // GET api/test

        /// <summary>
        /// 구하기
        /// </summary>
        /// <returns>문자열 리스트</returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<TestModel>>> Get()
        {
            return await this.context.Test.ToListAsync();
        }

        #endregion
    }
}
728x90
반응형
그리드형(광고전용)
Posted by 사용자 icodebroker

댓글을 달아 주세요