tags:

views:

1292

answers:

6

I've got the following SQL:

select * from transaction_log where stoptime like '%2008%'

How do I write this in LINQ to SQL syntax?

+18  A: 

If you want to use the literal method, it's like this:

var query = from l in transaction_log
            where SqlMethods.Like(l.stoptime, "%2008%")
            select l;

Another option is:

var query = from l in transaction_log
        where l.stoptime.Contains("2008")
        select l;

If it's a DateTime:

var query = from l in transaction_log
        where l.stoptime.Year = 2008
        select l;

That method is in the System.Data.Linq.SqlClient namespace

Nick Craver
cool. I'm off and running. I did have to typecast "stoptime" to a DateTime in order to access the Year property, but no big deal.
scottmarlowe
+1  A: 
from x in context.Table where x.Contains("2008") select x
Will
I'm not sure if this results in the proper Sql. You'd have to profile it to see.
Will
+1  A: 

If stoptime data type is string, you can use .Contains() function, and also .StartsWith() and .EndsWith().

ChRoss
A: 

If you use the contains to method then you are doing a LIKE '%somestring%'. If you use a startswith method then it is the same as 'somestring%'. Finally, endswith is the same as using '%somestring'.

To summarize, contains will find any pattern in the string but startswith and endswith will help you find matches at the beginning and end of the word.

A: 

The really interesting point is, that .NET creates queries like "Select * from table where name like '%test%'" when you use "from x in context.Table where x.Contains("test") select x" which is quite impressing

MADMap
A: 

Thanks--good answers.

This is, in fact, a DateTime type; I had to typecast "stoptime" as:

var query = from p in dbTransSummary.Transaction_Logs
    where ( (DateTime) p.StopTime).Year == dtRollUpDate.Year
    select

Minor point. It works great!

scottmarlowe