Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL: How to write a 'Like' select?

Tags:

I've got the following SQL:

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

How do I write this in LINQ to SQL syntax?

like image 540
Scott Marlowe Avatar asked Sep 18 '08 12:09

Scott Marlowe


People also ask

How can I use SQL like in LINQ?

In LINQ to SQL, we don't have a LIKE operator, but by using contains(), startswith(), and endswith() methods, we can implement LIKE operator functionality in LINQ to SQL.

How does a LINQ query transform to a SQL query?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.

How do you write a query in LINQ?

This query returns two groups based on the first letter of the word. List<int> numbers = new() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; // The query variables can also be implicitly typed by using var // Query #1. IEnumerable<int> filteringQuery = from num in numbers where num < 3 || num > 7 select num; // Query #2.

Is LINQ to SQL obsolete?

"As long as LINQ to SQL lives under Entity Framework, it's dead.


1 Answers

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

like image 72
Nick Craver Avatar answered Sep 20 '22 15:09

Nick Craver