Just a quick reference of a couple basic query conversions for Linq to SQL
Code Snippet
- //inner join
- //SELECT [t0].[CountyName]
- //FROM [dbo].[County] AS [t0]
- //INNER JOIN [dbo].[State] AS [t1] ON [t0].[StateID] = [t1].[StateID]
- //WHERE LOWER([t1].[StateName]) = @p0
- var counties = from c in db.Counties
- join st in db.States on c.StateID equals st.StateID
- where st.StateName.ToLower().Equals("florida")
- select c.CountyName;
- //left join -- use DefaultIfEmpty and new object
- //SELECT [t0].[CountyName],
- //(CASE WHEN [t2].[test] IS NULL THEN CONVERT(NVarChar(50),@p0)
- // ELSE CONVERT(NVarChar(50),[t2].[StateName])
- // END) AS [StateName]
- //FROM [dbo].[County] AS [t0]
- //LEFT OUTER JOIN
- //(
- // SELECT 1 AS [test], [t1].[StateID], [t1].[StateName]
- // FROM [dbo].[State] AS [t1]
- //) AS [t2] ON [t0].[StateID] = [t2].[StateID]
- var counties2 = from c in db.Counties
- join st in db.States on c.StateID equals st.StateID
- into stateCounties
- from co in stateCounties.DefaultIfEmpty()
- select new { CountyName = c.CountyName, StateName = (co == null)? "": co.StateName };
- //Same table query
- //SELECT [t0].[CountyName]
- //FROM [dbo].[County] AS [t0],
- // [dbo].[County] AS [t1]
- //WHERE ([t0].[CountyName] = [t1].[CountyName]) AND ([t0].[CountyID] <> [t1].[CountyID])
- var counties3 = from c1 in db.Counties
- from c2 in db.Counties
- where c1.CountyName == c2.CountyName && c1.CountyID != c2.CountyID
- select new
- {
- CountyName = c1.CountyName,
- };
- var counties4 = (from c1 in db.Counties
- from c2 in db.Counties
- where c1.CountyName == c2.CountyName && c1.CountyID != c2.CountyID
- group c1 by c1.CountyName into dups
- select new
- {
- CountyName = dups.Key,
- Count = dups.Count()
- }
- ).OrderBy(n => n.CountyName);
Some resources I found useful:
http://codesamplez.com/database/linq-to-sql-join-tutorials
http://weblogs.asp.net/rajbk/archive/2010/03/12/joins-in-linq-to-sql.aspx
http://msdn.microsoft.com/en-us/library/bb386913.aspx
More specifically to joins:
http://msdn.microsoft.com/en-us/library/bb399397.aspx
No comments:
Post a Comment