Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

Entity Framework의 Join 사용 시 다중 칼럼에 대한 OR 조건 쿼리

다음과 같은 질문이 있군요.

안녕하세요! EntityFramework Linq 질문 드리겠습니다.
; https://www.sysnet.pe.kr/3/0/5558

간단하게 테스트를 위해 다음의 글을 참조해,

Tutorial: Get Started with Entity Framework 6 Code First using MVC 5
; https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

(위의 글은 EF를 사용했지만) Entity Framework Core를 이용한 콘솔 프로젝트를 만들어 보겠습니다. 우선 .NET Core/5+ 프로젝트를 만들고 참조를 2개 추가합니다.

Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer

그다음 엔티티 타입으로 Student와 Book을 추가하고,

using System.Collections.Generic;

namespace ConsoleApp1
{
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int SubID { get; set; } // JOIN OR 테스트를 위한 칼럼 추가

        public virtual ICollection<Book> Enrollments { get; set; }
    }

    public class Book
    {
        public int ID { get; set; }
        public int StudentID { get; set; }
        public string Title { get; set; }
        public int SubID { get; set; } // JOIN OR 테스트를 위한 칼럼 추가
    }
}

DbContext를 이렇게 구성해 주면 됩니다.

using Microsoft.EntityFrameworkCore;

namespace ConsoleApp1
{
    public class SchoolContext : DbContext
    {

        public SchoolContext() : base()
        {
        }

        public DbSet<Student> Students { get; set; }
        public DbSet<Book> Books { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);

            string cs = "Data Source=.;Initial Catalog=ContosoUniversity1;Integrated Security=SSPI;";
            optionsBuilder.UseSqlServer(cs);
        }
    }
}

마지막으로 다음과 같이 예제 데이터와 함께 DB를 생성하는 코드를 추가하면 준비가 완료됩니다. ^^

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            SchoolContext db = new SchoolContext();

            // EF 6는 https://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx
            if (db.Database.CanConnect() == false)
            {
                db.Database.EnsureCreated();
                InsertSampleData(db);
            }
        }

        private static void InsertSampleData(SchoolContext context)
        {
            var students = new List<Student>
                       {
                           new Student{Name="Carson",SubID=1},
                           new Student{Name="Meredith",SubID=2},
                           new Student{Name="Arturo",SubID=3},
                           new Student{Name="Gytis",SubID=1},
                           new Student{Name="Yan",SubID=2},
                           new Student{Name="Peggy",SubID=3},
                           new Student{Name="Laura",SubID=1},
                           new Student{Name="Nino",SubID=2}
                       };

            students.ForEach(s => context.Students.Add(s));
            context.SaveChanges();
            var courses = new List<Book>
                       {
                           new Book{StudentID=1, Title="Book 1", SubID=1},
                           new Book{StudentID=1, Title="Book 1", SubID=1},
                           new Book{StudentID=1, Title="Book 1", SubID=2},
                           new Book{StudentID=2, Title="Book 2", SubID=2},
                           new Book{StudentID=2, Title="Book 2", SubID=3},
                           new Book{StudentID=2, Title="Book 2", SubID=3},
                           new Book{StudentID=3, Title="Book 3", SubID=4},
                           new Book{StudentID=4, Title="Book 4", SubID=4},
                           new Book{StudentID=4, Title="Book 4", SubID=5},
                           new Book{StudentID=5, Title="Book 5", SubID=5},
                           new Book{StudentID=6, Title="Book 6", SubID=6},
                           new Book{StudentID=7, Title="Book 7", SubID=6},
                       };
            courses.ForEach(s => context.Books.Add(s));
            context.SaveChanges();
        }

    }
}




자, 이제 본격적으로 INNER JOIN 테스트를 해볼까요? ^^ 다들 아시겠지만 기본적인 JOIN은 LINQ 쿼리로 다음과 같이 작성할 수 있습니다.

{
    var q = from s in db.Students
            join e in db.Books on s.ID equals e.StudentID
            select s;

    Console.WriteLine(q.ToQueryString());
}
/* 출력 결과
SELECT [s].[ID], [s].[Name], [s].[SubID]
FROM [Students] AS [s]
INNER JOIN [Books] AS [b] ON [s].[ID] = [b].[StudentID]     
*/

이 상태에서 JOIN의 AND 조건을 추가하는 것은 다음과 같이 on과 equals에 다중 AND 조건을 매칭시키는 방식으로 쉽게 구현할 수 있습니다.

{
    var q = from s in db.Students
            join e in db.Books on new { C1 = s.ID, C2 = s.SubID }
                           equals new { C1 = e.StudentID, C2 = e.SubID }
            select s;

    Console.WriteLine(q.ToQueryString());
}
/*
SELECT [s].[ID], [s].[Name], [s].[SubID]
FROM [Students] AS [s]
INNER JOIN [Books] AS [b] ON ([s].[ID] = [b].[StudentID]) AND ([s].[SubID] = [b].[SubID])
*/

그런데, "안녕하세요! EntityFramework Linq 질문 드리겠습니다." 질문 글에서는 JOIN에 대해 OR 조건을 추가하고 싶다는 것입니다. 아쉽게도 OR 조건을 직접 명시하는 방법은 없습니다.

하지만 가만 생각해 보면, INNER JOIN의 OR 조건 추가는 사실상 CROSS JOIN과 다를 바가 없습니다. 따라서 다음과 같은 LINQ 쿼리로 구현해도 동일한 resultset을 반환받게 됩니다.

{
    var q = from s in db.Students
            from e in db.Books
            where s.ID == e.StudentID || e.SubID == s.SubID
            select s;

    Console.WriteLine(q.ToQueryString());
}
/* 출력 결과
SELECT [s].[ID], [s].[Name], [s].[SubID]
FROM [Students] AS [s]
CROSS JOIN [Books] AS [b]
WHERE ([s].[ID] = [b].[StudentID]) OR ([b].[SubID] = [s].[SubID])
*/

실제로 위에서 출력한 SELECT 문과 다음의 SELECT 문은 완전히 동일한 결과를 반환합니다.

SELECT [s].[ID], [s].[Name], [s].[SubID]
FROM [Students] AS [s]
INNER JOIN [Books] AS [b] ON ([s].[ID] = [b].[StudentID]) OR ([b].[SubID] = s.SubID)

그나저나, 사실 저도 실무에서 CROSS JOIN을 이제껏 단 한 번도 써본 적이 없습니다. 아마도 LINQ 쿼리의 JOIN에 대한 OR 조건을 검색해 보면 거의 안 나온 이유가 저런 식의 (CROSS JOIN 결과를 낳는) INNER JOIN ... OR을 거의 쓰는 일이 없기 때문일 듯합니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 1/28/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13854정성태12/27/20245851C/C++: 186. Golang - 콘솔 응용 프로그램을 NT 서비스를 지원하도록 변경파일 다운로드1
13853정성태12/26/20244793디버깅 기술: 213. Windbg - swapgs 명령어와 (Ring 0 커널 모드의) FS, GS Segment 레지스터
13852정성태12/25/20245886디버깅 기술: 212. Windbg - (Ring 3 사용자 모드의) FS, GS Segment 레지스터파일 다운로드1
13851정성태12/23/20245094디버깅 기술: 211. Windbg - 커널 모드 디버깅 상태에서 사용자 프로그램을 디버깅하는 방법
13850정성태12/23/20246205오류 유형: 940. "Application Information" 서비스를 중지한 경우, "This file does not have an app associated with it for performing this action."
13849정성태12/20/20246182디버깅 기술: 210. Windbg - 논리(가상) 주소를 Segmentation을 거쳐 선형 주소로 변경
13848정성태12/18/20245679디버깅 기술: 209. Windbg로 알아보는 Prototype PTE파일 다운로드2
13847정성태12/18/20245754오류 유형: 939. golang - 빌드 시 "unknown directive: toolchain" 오류 빌드 시 이런 오류가 발생한다면?
13846정성태12/17/20246299디버깅 기술: 208. Windbg로 알아보는 Trans/Soft PTE와 2가지 Page Fault 유형파일 다운로드1
13845정성태12/16/20245156디버깅 기술: 207. Windbg로 알아보는 PTE (_MMPTE)
13844정성태12/14/20246654디버깅 기술: 206. Windbg로 알아보는 PFN (_MMPFN)파일 다운로드1
13843정성태12/13/20245182오류 유형: 938. Docker container 내에서 빌드 시 error MSB3021: Unable to copy file "..." to "...". Access to the path '...' is denied.
13842정성태12/12/20245366디버깅 기술: 205. Windbg - KPCR, KPRCB
13841정성태12/11/20245979오류 유형: 937. error MSB4044: The "ValidateValidArchitecture" task was not given a value for the required parameter "RemoteTarget"
13840정성태12/11/20245261오류 유형: 936. msbuild - Your project file doesn't list 'win' as a "RuntimeIdentifier"
13839정성태12/11/20246179오류 유형: 936. msbuild - error CS1617: Invalid option '12.0' for /langversion. Use '/langversion:?' to list supported values.
13838정성태12/4/20245939오류 유형: 935. Windbg - Breakpoint 0's offset expression evaluation failed.
13837정성태12/3/20246738디버깅 기술: 204. Windbg - 윈도우 핸들 테이블 (3) - Windows 10 이상인 경우
13836정성태12/3/20245285디버깅 기술: 203. Windbg - x64 가상 주소를 물리 주소로 변환 (페이지 크기가 2MB인 경우)
13835정성태12/2/20246709오류 유형: 934. Azure - rm: cannot remove '...': Directory not empty
13834정성태11/29/20246696Windows: 275. C# - CUI 애플리케이션과 Console 윈도우 (Windows 10 미만의 Classic Console 모드인 경우) [1]파일 다운로드1
13833정성태11/29/20246061개발 환경 구성: 737. Azure Web App에서 Scale-out으로 늘어난 리눅스 인스턴스에 SSH 접속하는 방법
13832정성태11/27/20245694Windows: 274. Windows 7부터 도입한 conhost.exe
13831정성태11/27/20245055Linux: 111. eBPF - BPF_MAP_TYPE_PERF_EVENT_ARRAY, BPF_MAP_TYPE_RINGBUF에 대한 다양한 용어들
13830정성태11/25/20246562개발 환경 구성: 736. 파이썬 웹 앱을 Azure App Service에 배포하기
13829정성태11/25/20246665스크립트: 67. 파이썬 - Windows 버전에서 함께 설치되는 py.exe
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...