[C#/COMMON/.NETCORE] dotnet tool install 명령 : Entity Framework Core 업데이트하기
■ dotnet tool install 명령을 사용해 Entity Framework Core를 업데이트하는 방법을 보여준다. 1. [명령 프롬프트]를 실행한다. 2. [명령 프롬프트]에서 아래 명령을 실행한다.
■ dotnet tool install 명령을 사용해 Entity Framework Core를 업데이트하는 방법을 보여준다. 1. [명령 프롬프트]를 실행한다. 2. [명령 프롬프트]에서 아래 명령을 실행한다.
■ dotnet ef 명령을 사용해 Entity Framework Core 버전을 확인하는 방법을 보여준다. 1. [명령 프롬프트]를 실행한다. 2. [명령 프롬프트]에서 아래 명령을 실행한다.
■ dotnet ef 명령을 사용해 Entity Framework Core 설치 여부를 확인하는 방법을 보여준다. 1. [명령 프롬프트]를 실행한다. 2. [명령 프롬프트]에서 아래 명령을
■ IdentityServer4 신원 서버에서 사용자 인증하고 API를 호출하는 방법을 보여준다. (SQL SERVER 사용) [TestIdentityServer 프로젝트] ▶ Properties.launchSettins.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
{ "iisSettings" : { "windowsAuthentication" : false, "anonymousAuthentication" : true, "iisExpress" : { "applicationUrl" : "http://localhost:50000", "sslPort" : 44300 } }, "profiles" : { "IIS Express" : { "commandName" : "IISExpress", "launchBrowser" : true, "environmentVariables" : { "ASPNETCORE_ENVIRONMENT" : "Development" } }, "TestIdentityServer" : { "commandName" : "Project", "launchBrowser" : true, "applicationUrl" : "https://localhost:5001;http://localhost:5000", "environmentVariables" : { "ASPNETCORE_ENVIRONMENT" : "Development" } } } } |
▶ appsettings.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
{ "Logging" : { "LogLevel" : { "Default" : "Information", "Microsoft" : "Warning", "Microsoft.Hosting.Lifetime" : "Information" } }, "AllowedHosts" : "*", "ConnectionStrings" : { "DefaultConnection" : "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=TestDB;Integrated Security=True;" } } |
▶
■ IdentityServer4.EntityFramework 누겟을 설치하는 방법을 보여준다. 1. Visual Studio를 실행한다. 2. [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 실행한다.
■ Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore 누겟을 설치하는 방법을 보여준다. 1. Visual Studio를 실행한다. 2. [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 실행한다.
■ ConfigurationProvider 클래스에서 커스텀 구성 공급자를 사용하는 방법을 보여준다. (SQL SERVER 사용) ▶ Models/Configuration.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
namespace TestProject.Models { /// <summary> /// 구성 /// </summary> public class Configuration { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public string ID { get; set; } #endregion #region 값 - Value /// <summary> /// 값 /// </summary> public string Value { get; set; } #endregion } } |
▶ Data/DatabaseContext.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
using Microsoft.EntityFrameworkCore; using TestProject.Models; namespace TestProject.Data { /// <summary> /// 데이터베이스 /// </summary> public class DatabaseContext : DbContext { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 구성 - Configuration /// <summary> /// 구성 /// </summary> public DbSet<Configuration> Configuration { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - DatabaseContext(options) /// <summary> /// 생성자 /// </summary> /// <param name="options">옵션</param> public DatabaseContext(DbContextOptions options) : base(options) { } #endregion } } |
▶ CustomConfigurationProvider.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; using TestProject.Data; using TestProject.Models; namespace TestProject { /// <summary> /// 커스텀 구성 공급자 /// </summary> public class CustomConfigurationProvider : ConfigurationProvider { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 옵션 액션 - OptionsAction /// <summary> /// 옵션 액션 /// </summary> Action<DbContextOptionsBuilder> OptionsAction { get; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - CustomConfigurationProvider(optionsAction) /// <summary> /// 생성자 /// </summary> /// <param name="optionsAction"></param> public CustomConfigurationProvider(Action<DbContextOptionsBuilder> optionsAction) { OptionsAction = optionsAction; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 로드하기 - Load() /// <summary> /// 로드하기 /// </summary> public override void Load() { DbContextOptionsBuilder<DatabaseContext> builder = new DbContextOptionsBuilder<DatabaseContext>(); OptionsAction(builder); using(DatabaseContext context = new DatabaseContext(builder.Options)) { context.Database.EnsureCreated(); if(!context.Configuration.Any()) { Data = CreateData(context); } else { Data = context.Configuration.ToDictionary ( configuration => configuration.ID, configuration => configuration.Value ); } } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 데이터 생성하기 - CreateData(context) /// <summary> /// 데이터 생성하기 /// </summary> /// <param name="context">데이터베이스 컨텍스트</param> /// <returns>데이터</returns> private static IDictionary<string, string> CreateData(DatabaseContext context) { Dictionary<string, string> sourceDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "Key1", "Value1" }, { "Key2", "Value2" }, { "Key3", "Value3" } }; context.Configuration.AddRange ( sourceDictionary.Select ( keyValuePair => new Configuration { ID = keyValuePair.Key, Value = keyValuePair.Value } ) .ToArray() ); context.SaveChanges(); return sourceDictionary; } #endregion } } |
▶
■ ConfigurationProvider 클래스에서 커스텀 구성 공급자를 사용하는 방법을 보여준다. (인메모리 데이터베이스 사용) ▶ Models/Configuration.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
namespace TestProject.Models { /// <summary> /// 구성 /// </summary> public class Configuration { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public string ID { get; set; } #endregion #region 값 - Value /// <summary> /// 값 /// </summary> public string Value { get; set; } #endregion } } |
▶ Data/DatabaseContext.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
using Microsoft.EntityFrameworkCore; using TestProject.Models; namespace TestProject.Data { /// <summary> /// 데이터베이스 /// </summary> public class DatabaseContext : DbContext { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 구성 - Configuration /// <summary> /// 구성 /// </summary> public DbSet<Configuration> Configuration { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - DatabaseContext(options) /// <summary> /// 생성자 /// </summary> /// <param name="options">옵션</param> public DatabaseContext(DbContextOptions options) : base(options) { } #endregion } } |
▶ CustomConfigurationProvider.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; using TestProject.Data; using TestProject.Models; namespace TestProject { /// <summary> /// 커스텀 구성 공급자 /// </summary> public class CustomConfigurationProvider : ConfigurationProvider { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 옵션 액션 - OptionsAction /// <summary> /// 옵션 액션 /// </summary> Action<DbContextOptionsBuilder> OptionsAction { get; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - CustomConfigurationProvider(optionsAction) /// <summary> /// 생성자 /// </summary> /// <param name="optionsAction"></param> public CustomConfigurationProvider(Action<DbContextOptionsBuilder> optionsAction) { OptionsAction = optionsAction; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 로드하기 - Load() /// <summary> /// 로드하기 /// </summary> public override void Load() { DbContextOptionsBuilder<DatabaseContext> builder = new DbContextOptionsBuilder<DatabaseContext>(); OptionsAction(builder); using(DatabaseContext context = new DatabaseContext(builder.Options)) { context.Database.EnsureCreated(); if(!context.Configuration.Any()) { Data = CreateData(context); } else { Data = context.Configuration.ToDictionary ( configuration => configuration.ID, configuration => configuration.Value ); } } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 데이터 생성하기 - CreateData(context) /// <summary> /// 데이터 생성하기 /// </summary> /// <param name="context">데이터베이스 컨텍스트</param> /// <returns>데이터</returns> private static IDictionary<string, string> CreateData(DatabaseContext context) { Dictionary<string, string> sourceDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "Key1", "Value1" }, { "Key2", "Value2" }, { "Key3", "Value3" } }; context.Configuration.AddRange ( sourceDictionary.Select ( keyValuePair => new Configuration { ID = keyValuePair.Key, Value = keyValuePair.Value } ) .ToArray() ); context.SaveChanges(); return sourceDictionary; } #endregion } } |
▶
■ SqlServerDbContextOptionsExtensions 클래스의 UseSqlServer 확장 메소드를 사용해 SQL Server를 사용하는 방법을 보여준다. ▶ Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
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.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")); } ); services.AddRazorPages(); } #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(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } #endregion } } |
■ InMemoryDbContextOptionsExtensions 클래스의 UseInMemoryDatabase 확장 메소드를 사용해 인메모리 데이터베이스를 사용하는 방법을 보여준다. ▶ Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
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 } } |
■ EntityFrameworkServiceCollectionExtensions 클래스의 AddDbContext 확장 메소드를 사용해 DB 컨텍스트를 서비스로 등록하는 방법을 보여준다. ▶ Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
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 } } |
■ Entity Framework Core를 사용해 인메모리 데이터베이스를 접속하는 방법을 보여준다. ▶ Models/TestModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
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 } } |
▶ Models/TestData.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
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 } } |
▶ Data/DatabaseContext.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
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 } } |
■ ServiceProviderServiceExtensions 클래스의 GetRequiredService<T> 확장 메소드를 사용해 데이터베이스 컨텍스트를 구하는 방법을 보여준다. ▶ Models/MovieData.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Linq; using TestProject.Data; namespace TestProject.Models { /// <summary> /// 영화 데이터 /// </summary> public static class MovieData { //////////////////////////////////////////////////////////////////////////////////////////////////// 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.Movie.Any()) { return; } context.Movie.AddRange ( new Movie { Title = "When Harry Met Sally", ReleaseDate = DateTime.Parse("1989-2-12"), Genre = "Romantic Comedy", Price = 7.99M }, new Movie { Title = "Ghostbusters ", ReleaseDate = DateTime.Parse("1984-3-13"), Genre = "Comedy", Price = 8.99M }, new Movie { Title = "Ghostbusters 2", ReleaseDate = DateTime.Parse("1986-2-23"), Genre = "Comedy", Price = 9.99M }, new Movie { Title = "Rio Bravo", ReleaseDate = DateTime.Parse("1959-4-15"), Genre = "Western", Price = 3.99M } ); context.SaveChanges(); } } #endregion } } |
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
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 //////////////////////////////////////////////////////////////////////////////// Public #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 { MovieData.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 } } |
※ TestDB 데이터베이스 생성
■ dotnet ef database update 명령을 사용해 데이터베이스 및 스키마를 만드는 방법을 보여준다. 1. [명령 프롬프트]를 실행한다. 2. [명령 프롬프트]에서 아래 명령을
■ dotnet ef migrations add 명령을 사용해 마이그레이션을 준비하는 방법을 보여준다. 1. [명령 프롬프트]를 실행한다. 2. [명령 프롬프트]에서 아래 명령을 실행한다. ▶
■ Entity Framework Core를 사용해 SQL Server 접속하기 1. 비주얼 스튜디오를 실행한다. 2. [Visual Studio 2019] 대화 상자에서 [새 프로젝트 만들기] 항목을
■ Microsoft.EntityFrameworkCore.Design 누겟을 설치하는 방법을 보여준다. 1. Visual Studio를 실행한다. 2. [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 실행한다.
■ Microsoft.EntityFrameworkCore.SqlServer 누겟을 설치하는 방법을 보여준다. 1. Visual Studio를 실행한다. 2. [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 실행한다.
■ Microsoft.EntityFrameworkCore.SQLite 누겟을 설치하는 방법을 보여준다. 1. Visual Studio를 실행한다. 2. [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 실행한다.
■ dotnet tool install 명령을 사용해 Entity Framework Core 도구를 설치하는 방법을 보여준다. 1. [명령 프롬프트]를 실행한다. 2. [명령 프롬프트]에서 아래 명령을
■ Microsoft.EntityFrameworkCore.InMemory 누겟을 설치하는 방법을 보여준다. 1. Visual Studio를 실행한다. 2. [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 실행한다.
■ 엔터티 프레임워크(Entity Framework)를 사용해 ASP.NET MVC 애플리케이션을 만드는 방법을 보여준다. ▶ Room.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
using System.Collections.Generic; namespace TestProject.Models { /// <summary> /// 회의실 /// </summary> public class Room { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 회의실 ID - RoomID /// <summary> /// 회의실 ID /// </summary> public int RoomID { get; set; } #endregion #region 명칭 - Name /// <summary> /// 명칭 /// </summary> public string Name { get; set; } #endregion #region 스피커 컬렉션 - SpeakerCollection /// <summary> /// 스피커 컬렉션 /// </summary> public virtual ICollection<Speaker> SpeakerCollection { get; set; } #endregion } } |
▶ Speaker.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
namespace TestProject.Models { /// <summary> /// 스피커 /// </summary> public class Speaker { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 스피커 ID - SpeakerID /// <summary> /// 스피커 ID /// </summary> public int SpeakerID { get; set; } #endregion #region 명칭 - Name /// <summary> /// 명칭 /// </summary> public string Name { get; set; } #endregion #region 회의실 ID - RoomID /// <summary> /// 회의실 ID /// </summary> public int RoomID { get; set; } #endregion #region 회의실 - Room /// <summary> /// 회의실 /// </summary> public virtual Room Room { get; set; } #endregion } } |
▶ TestProjectContext.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
using System.Data.Entity; using TestProject.Models; namespace TestProject.Data { /// <summary> /// 테스트 프로젝트 컨텍스트 /// </summary> public class TestProjectContext : DbContext { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 방 DB 집합 - RoomDBSet /// <summary> /// 방 DB 집합 /// </summary> public DbSet<Room> RoomDBSet { get; set; } #endregion #region 스피커 DB 집합 - SpeakerDBSet /// <summary> /// 스피커 DB 집합 /// </summary> public DbSet<Speaker> SpeakerDBSet { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - TestProjectContext() /// <summary> /// 생성자 /// </summary> public TestProjectContext() : base("name=TestProjectContext") { } #endregion } } |
▶ HomeController.cs