あなたは良いスタートをしていますが、自分でトリプルジョインをしない方が良いと思います。 Linq-to-SQLは、あなたのための詳細を処理できます。クエリのアスペクトを1秒遅らせて、望みの結果から始めれば、よりうまくいくでしょう。私が言うことから、あなたが望む目的のタイプはブランドのリストであり、各ブランドはそのソースのリストを含むべきです。ここでは、(LinqPadをダウンロードして起動する)それを行う方法です...
// LinqPad C# statement(s)
var results =
from b in Brands
select new {
Brand = b,
Sources = (
from s in Sources
join xref in BrandSources on s.SourceID equals xref.SourceID
where xref.BrandID == b.BrandID
select s
).ToList()
};
result.Dump(); // show result in LinqPad
LinqPadが、これは、単一のクエリで実行されることを示しているが、あなたの結果オブジェクトであなたのList<Source>
を組み立てるの根性が舞台裏で起こります。ここでLinqPadが実行されるものです:
SELECT [t0].[BrandID], [t0].[Name], [t1].[SourceID], [t1].[SourceName], [t1].[Image], (
SELECT COUNT(*)
FROM [Source] AS [t3]
INNER JOIN [BrandSource] AS [t4] ON [t3].[SourceID] = [t4].[SourceID]
WHERE [t4].[BrandID] = [t0].[BrandID]
) AS [value]
FROM [Brand] AS [t0]
LEFT OUTER JOIN ([Source] AS [t1]
INNER JOIN [BrandSource] AS [t2] ON [t1].[SourceID] = [t2].[SourceID]) ON [t2].[BrandID] = [t0].[BrandID]
そしてここではいくつかのテストデータは、自宅で一緒に、次の人のためだ。何であなたはブランドの#3のソースの空のリストにこの方法を取得することを
create table Brand (
BrandID int,
Name varchar(50),
)
create table BrandSource (
BrandID int,
SourceID int
)
create table Source (
SourceID int,
SourceName varchar(50),
[Image] varchar(50)
)
insert into Brand select 1, 'Brand1'
insert into Brand select 2, 'Brand2'
insert into Brand select 3, 'Brand3'
insert into Source select 1, 'Source1', 'src1.gif'
insert into Source select 2, 'Source2', 'src2.jpg'
insert into Source select 3, 'Source3', 'src3.bmp'
insert into Source select 4, 'Source4', 'src4.png'
insert into Source select 5, 'Source5', 'src5.raw'
insert into BrandSource select 1, 1
insert into BrandSource select 1, 2
insert into BrandSource select 1, 3
insert into BrandSource select 2, 2
insert into BrandSource select 2, 4
select * from Brand
select * from BrandSource
select * from Source
お知らせ、私はあなたが望むと思う。元のクエリINNER JOIN
ブランド#3離れてしまった。
最後に、ここにあなたがあなたのクエリの結果を使用したい方法の例です:
foreach (var result in results) {
string chk = (result.Brand.Active ? " checked='checked'" : "");
var buf = new StringBuilder();
buf.Append("<tr>");
buf.AppendFormat("<td><input type='checkbox'{0}></td>", chk);
buf.AppendFormat("<td width='1%'><img width='50px' src='{0}'></img></td>", result.Brand.Image);
buf.AppendFormat("<td>{0}</td>", result.Brand.Name);
buf.Append("<td>");
foreach(var src in result.Sources) {
buf.AppendFormat("<img src='{0}'></img>", src.Image);
}
buf.Append("</td>");
buf.Append("</tr>");
resultSpan.InnerHtml = buf.ToString();
}
これは私が探していたものです。ありがとうございました。 –