LINQ to SQL : 여러 열에서 여러 조인 이게 가능해?
주어진:
TABLE_1
다음 열로 명명 된 테이블 :
ID
ColumnA
ColumnB
ColumnC
어디 SQL 쿼리를 TABLE_1
두 번 오프의 기반 자체 조인 ColumnA
, ColumnB
, ColumnC
. 쿼리는 다음과 같습니다.
Select t1.ID, t2.ID, t3.ID
From TABLE_1 t1
Left Join TABLE_1 t2 On
t1.ColumnA = t2.ColumnA
And t1.ColumnB = t2.ColumnB
And t1.ColumnC = t2.ColumnC
Left Join TABLE_1 t3 On
t2.ColumnA = t3.ColumnA
And t2.ColumnB = t3.ColumnB
And t2.ColumnC = t3.ColumnC
... and query continues on etc.
문제:
LINQ에서 해당 쿼리를 다시 작성해야합니다. 나는 그것을 찌르려고 노력했다.
var query =
from t1 in myTABLE1List // List<TABLE_1>
join t2 in myTABLE1List
on t1.ColumnA equals t2.ColumnA
&& t1.ColumnB equals t2.ColumnA
// ... and at this point intellisense is making it very obvious
// I am doing something wrong :(
LINQ에서 쿼리를 작성하려면 어떻게합니까? 내가 뭘 잘못하고 있죠?
Linq의 여러 열을 SQL에 조인하는 것은 약간 다릅니다.
var query =
from t1 in myTABLE1List // List<TABLE_1>
join t2 in myTABLE1List
on new { t1.ColumnA, t1.ColumnB } equals new { t2.ColumnA, t2.ColumnB }
...
익명 유형을 활용하고 비교하려는 여러 열에 대한 유형을 작성해야합니다.
이것은 처음에는 혼란스러워 보이지만 일단 SQL이 표현식에서 구성되는 방식에 익숙해지면 훨씬 더 의미가 있습니다. 커버 아래에서 원하는 조인 유형을 생성합니다.
편집 주석을 기반으로 두 번째 조인의 예를 추가합니다.
var query =
from t1 in myTABLE1List // List<TABLE_1>
join t2 in myTABLE1List
on new { A = t1.ColumnA, B = t1.ColumnB } equals new { A = t2.ColumnA, B = t2.ColumnB }
join t3 in myTABLE1List
on new { A = t2.ColumnA, B = t2.ColumnB } equals new { A = t3.ColumnA, B = t3.ColumnB }
...
Title_Authors는 한 번의 프로젝트 결과에 참여하고 체인을 계속하는 두 가지를 찾습니다.
DataClasses1DataContext db = new DataClasses1DataContext();
var queryresults = from a in db.Authors
join ba in db.Title_Authors
on a.Au_ID equals ba.Au_ID into idAuthor
from c in idAuthor
join t in db.Titles
on c.ISBN equals t.ISBN
select new { Author = a.Author1,Title= t.Title1 };
foreach (var item in queryresults)
{
MessageBox.Show(item.Author);
MessageBox.Show(item.Title);
return;
}
LINQ2SQL에서는 내부 조인을 사용할 때 명시 적으로 조인 할 필요가 없습니다.
데이터베이스에 적절한 외래 키 관계가있는 경우 LINQ 디자이너에서 관계를 자동으로 얻습니다 (그렇지 않으면 디자이너에서 수동으로 관계를 만들 수는 있지만 실제로 데이터베이스에 적절한 관계가 있어야 함)
그런 다음 "점 표기법"으로 관련 테이블에 액세스 할 수 있습니다.
var q = from child in context.Childs
where child.Parent.col2 == 4
select new
{
childCol1 = child.col1,
parentCol1 = child.Parent.col1,
};
쿼리를 생성합니다
SELECT [t0].[col1] AS [childCol1], [t1].[col1] AS [parentCol1]
FROM [dbo].[Child] AS [t0]
INNER JOIN [dbo].[Parent] AS [t1] ON ([t1].[col1] = [t0].[col1]) AND ([t1].[col2] = [t0].[col2])
WHERE [t1].[col2] = @p0
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [4]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1
내 의견으로는 이것은 훨씬 더 읽기 쉽고 실제 조인 메커니즘이 아닌 특별한 조건에 집중할 수있게합니다.
Edit
This is of course only applicable when you want to join in the line with our database model. If you want to join "outside the model" you need to resort to manual joins as in the answer from Quintin Robinson
U can also use :
var query =
from t1 in myTABLE1List
join t2 in myTABLE1List
on new { ColA=t1.ColumnA, ColB=t1.ColumnB } equals new { ColA=t2.ColumnA, ColB=t2.ColumnB }
join t3 in myTABLE1List
on new {ColC=t2.ColumnA, ColD=t2.ColumnB } equals new { ColC=t3.ColumnA, ColD=t3.ColumnB }
I would like to give another example in which multiple (3) joins are used.
DataClasses1DataContext ctx = new DataClasses1DataContext();
var Owners = ctx.OwnerMasters;
var Category = ctx.CategoryMasters;
var Status = ctx.StatusMasters;
var Tasks = ctx.TaskMasters;
var xyz = from t in Tasks
join c in Category
on t.TaskCategory equals c.CategoryID
join s in Status
on t.TaskStatus equals s.StatusID
join o in Owners
on t.TaskOwner equals o.OwnerID
select new
{
t.TaskID,
t.TaskShortDescription,
c.CategoryName,
s.StatusName,
o.OwnerName
};
You can also join if the number of columns are not same in both tables and can map static value to table column
from t1 in Table1
join t2 in Table2
on new {X = t1.Column1, Y = 0 } on new {X = t2.Column1, Y = t2.Column2 }
select new {t1, t2}
In my opinion, this is the simplest way to join two tables with multiple fields:
from a in Table1 join b in Table2
on (a.Field1.ToString() + "&" + a.Field2.ToString())
equals (b.Field1.ToString() + "&" + b.Field2.ToString())
select a
You can write your query like this.
var query = from t1 in myTABLE1List // List<TABLE_1>
join t2 in myTABLE1List
on t1.ColumnA equals t2.ColumnA
and t1.ColumnB equals t2.ColumnA
If you want to compare your column with multiple columns.
'IT박스' 카테고리의 다른 글
Visual Studio에서 디버그 모드로 NUnit을 어떻게 실행합니까? (0) | 2020.07.18 |
---|---|
OpenSSL 연결을 거부하는 Homebrew (0) | 2020.07.18 |
CancellationToken이 CancellationTokenSource와 다른 이유는 무엇입니까? (0) | 2020.07.18 |
java.lang.OutOfMemoryError : Maven의 Java 힙 공간 (0) | 2020.07.18 |
git이 경로별로 하드 / 소프트 리셋을 수행 할 수없는 이유는 무엇입니까? (0) | 2020.07.17 |