티스토리 뷰

반응형

이전 포스트에서 마이그레이션을 Package Manager Console를 통해서 진행했습니다.

그런데, 마이그레이션 작접을 매번 PMC를 통해서 한다면 관리 포인트가 늘어나는 것 같은 느낌이라, 코드로 할 수 있는 방법이 없는지 찾아 보았습니다.

 

아래 코드는 StackOverflow에서 찾은 내용인데..어디였는지 링크를 잃어 버려서 추가하지는 못했습니다.

 

프로젝트는 ContosoPets3 프로젝트입니다.

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            using (IServiceScope scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                IEnumerable<string> assemblyMigrations = scope.ServiceProvider.GetService<ContosoPetsContext>().Database.GetMigrations();
                IEnumerable<string> appliedMigrations = scope.ServiceProvider.GetService<ContosoPetsContext>().Database.GetAppliedMigrations();
                IEnumerable<string> pendingMigrations = scope.ServiceProvider.GetService<ContosoPetsContext>().Database.GetPendingMigrations();

                //Check that all applied migrations exist in the assembly
                if (appliedMigrations.Any(a => !assemblyMigrations.Contains(a)))
                {
                    throw new Exception("There are applied migrations that do not exist in this assembly. All applied migrations must exist in the assembly. Aborting the migration.");
                }

                // Check that pending migrations will be applied chronologically after applied migrations
                IEnumerable<ulong> appliedTimestamps = appliedMigrations.Select(m => Convert.ToUInt64(m.Substring(0, 14)));
                IEnumerable<ulong> pendingTimestamps = pendingMigrations.Select(m => Convert.ToUInt64(m.Substring(0, 14)));
                if (appliedTimestamps.Any(a => pendingTimestamps.Any(p => a > p)))
                {
                    throw new Exception("There are pending migrations with a timestamp earlier than the timestamps of one or more applied migrations. Migrations must be applied chronologically. Aborting the migration.");
                }

                if (pendingMigrations.Any())
                {
                    scope.ServiceProvider.GetService<ContosoPetsContext>().Database.Migrate();
                }
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }

assemblyMigrations는 Database에 마이그레이션 이름들이고, appliedMigrations는 적용된 마이그레이션 이름들, pendingMigrations는 미적용된 마이그레이션 이름들을 가져와서 확인하고 미적용 마이그레이션이 있으면 적용을 자동으로 하도록 구성한 코드입니다.

 

실제로는 마이그레이션 작업이 매우 꼼꼼한 테스트를 거쳐서 실행이되어야 하니 이렇게 시작하자마자 있는 것이 아니라, 마이그레이션 확인 버튼을 누르면 확인을 진행하고 적용하도록 해야할 것 같습니다.

 

마이그레이션에 관한 더 자세한 내용은 아래 링크를 참고합니다.

Migrations Overview

Apply migrations at runtime

 

전체소스

kaki104/ContosoPets: Entity Framework Core 시작 sample (github.com)

 

kaki104/ContosoPets

Entity Framework Core 시작 sample. Contribute to kaki104/ContosoPets development by creating an account on GitHub.

github.com

 

반응형

'Entity Framework Core' 카테고리의 다른 글

SQL Style Guide (ko-KR)  (0) 2021.04.27
EF Core 동적 검색 조건 사용하기  (0) 2021.02.01
ADO.NET과 ORM 비교  (0) 2021.01.12
Entity Framework Core 시작(5/5)  (2) 2021.01.07
Entity Framework Core 시작(4/5)  (0) 2020.12.30
댓글