views:

50

answers:

2

I am almost done converting a MySQL app to Linq2SQL but struggling to get my head round this last SQL query

SELECT a.URL, b.URL AS DuplicateURL
FROM Pages a
INNER JOIN Pages b ON a.MetaDescription = b.MetaDescription
                   AND a.PageID <> b.PageID
WHERE a.DomainID = @reportid
  AND b.DomainID = @reportid
  AND LENGTH(TRIM(a.MetaDescription)) > 0
  AND a.URL < b.URL
ORDER BY a.URL ASC

Could anymore give me some syntax help on how I would create this query in Linq2SQL?

Any help greatly appreciated

+2  A: 

That's pretty straigtforward:

var reportId = ...;

var duplicates =
    from a in db.Pages
    from b in db.Pages
    where a.MetaDescription == b.MetaDescription
    where a.PageID != b.PageID
    where a.DomainID == reportId
    where b.DomainID == reportId
    where a.MetaDescription.Trim().Length > 0
    where a.URL < b.URL
    orderby a.URL
    select new { Url = a.URL, DuplicateUrl = b.Url }
Steven
Just a question, will `a.MetaDescription.Trim().Length` be translated to SQL okay? I ask because I haven't checked in my answer.
Lazarus
I haven't checked either, but the LINQ to SQL provider has a pretty solid query translator, so my guess is that this works. But please check.
Steven
According to LINQPAD `.Trim().Length > ` is translated to `LEN(LTRIM(RTRIM(.))) > `, but that was for a database I had at hand, not this one.
Mark Hurd
@Mark_Hurd That it translated it at all is the important thing, thanks for that!
Lazarus
+2  A: 

It goes like this:

var DuplicatePages = 
    from a in DBContext.Pages
    join b in DBContext.Pages on a.MetaDescription equals b.MetaDescription
    where (a.PageID <> b.PageID) && (a.DomainID == ReportID) && 
    (b.DomainID == ReportID) && (a.MetaDescription.Trim().Length > 0) && 
    (a.URL < b.URL)
    orderby a.URL
    select new { Url = a.URL, DuplicateUrl = b.URL };
Lazarus
Awesome thanks... Love this place, I learn so much!!
leen3o