none
SQL to Linq with Date Functions RRS feed

  • Question

  • How do I convert the following T-SQL for use with Linq:

    Select * from tBirthdays where datepart(month, Birthday) = 4 and datepart(yy, Birthday) = 2012

    Thursday, April 26, 2012 10:45 AM

Answers

  • Hi Gary.80;

    Because the Birthday is a datetime data type in the database table tBirthdays the following where clause will translate to datepart in the SQL query sent to the database. If the field Birthday is NOT nullable then remove the .Value in the two places in the where clause

    var results = from t in ContextName.tBirthdays
                  where t.Birthday.Value.Month == 4 && t.Birthday.Value.Year == 2012
                  select t;

      


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Thursday, April 26, 2012 2:54 PM

All replies

  • Hi Gary.80;

    Because the Birthday is a datetime data type in the database table tBirthdays the following where clause will translate to datepart in the SQL query sent to the database. If the field Birthday is NOT nullable then remove the .Value in the two places in the where clause

    var results = from t in ContextName.tBirthdays
                  where t.Birthday.Value.Month == 4 && t.Birthday.Value.Year == 2012
                  select t;

      


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Thursday, April 26, 2012 2:54 PM
  • What you need to do is use the date functions available in dot.net.

    For example (vb.net)

    Dim v = (From rf In dc.RFolders Where rf.UpdateDate.Value.Month = 4 Select rf).

    In above example the date field I am querying can be null so I am using the "value" property of the date field.  The second part of your query would use 

    Hope this helps

    Lloyd Sheen


    Lloyd Sheen

    Thursday, April 26, 2012 3:19 PM