3
var q = (from Labels in dc.tblArtworkDataLabels select Labels).ToList();

But I need this to do the quivalent of:

SELECT     d.ID, d.labelID, d.dataID, d.data, l.templateID
FROM         tblArtworkDataLabels AS d INNER JOIN
                      tblArtworkData AS l ON d.dataID = l.ID
WHERE     (l.templateID = 238)

How do I do this in LINQ?

Edit

Sorry! Missed the WHERE clause on original statmenet!

Community
  • 1
  • 1
Tom Gullen
  • 61,249
  • 84
  • 283
  • 456

3 Answers3

3
var result = dc.tblArtworkDataLabels
    .Join(dc.tblArtworkData, l => l.ID, d => d.dataID, (l, d) => new {l, d})
    .Select(o => new {
         Id = o.d.ID,
         LabelId = o.d.labelID,
         DataId = o.d.dataID, 
         Data = o.d.data, 
         TemplateId = o.l.templateID,
     })
    .Where(o => o.l.templateID == 238);
Snowbear
  • 16,924
  • 3
  • 43
  • 67
2

If you have a correct foreign key on tblArtworkData to the primary key on the tblArtworkDataLabels and have imported them correctly into the DBML designer you can have LINQ2SQL implicitly creating the join:

from l in tblArtworkData
where l.templateID = 238
select new {
    Id = l.tblArtworkDataLabel.ID,
    LabelId = l.tblArtworkDataLabel.labelID,
    DataId = l.tblArtworkDataLabel.dataID,
    Data = l.tblArtworkDataLabel.data,
    TemplateId = l.templateID,
}

See my answer on the question "LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?" for how the implicit join translates to SQL.

Edit:

In the case I misunderstood your relations and you have many tblArtworkDataLabels to one tblArtworkData you have to turn the query the other way around

from d in tblArtworkDataLabels
where d.tblArtworkData.templateID = 238
select new {
    Id = d.ID,
    LabelId = d.labelID,
    DataId = d.dataID,
    Data = d.data,
    TemplateId = d.tblArtworkData.templateID,
}
Community
  • 1
  • 1
Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108
1

try

var q = (from Labels in dc.tblArtworkDataLabels
         join data in dc.tblArtworkData on Labels.ID equals data.DataID select Labels).ToList();
Muhammad Adeel Zahid
  • 17,474
  • 14
  • 90
  • 155