Thursday 8 November 2012

how to use Like in asp.net using linq

ex1:

 SqlMethods.Like method

Digging into System.Data.Linq.SqlClient namespace, I found a little helper class called SqlMethods, which can be very usefull in such scenarios. SqlMethods has a method called Like, that can be used in a Linq to SQL query:

var query = from c in ctx.Customers
            where SqlMethods.Like(c.City, "L_n%")
            select c;
This method gets the string expression to check (the customer's city in this example) and the patterns to test against which is provided in the same way you'd write a LIKE clause in SQL.
Using the above query generated the required SQL statement:

SELECT CustomerID, CompanyName, ...
FROM    dbo.Customers
WHERE  City LIKE [L_n%]

ex2:
var query = (from emp in dc.Emps
   
                     where SqlMethods.Like(emp.ename, "%" + txtName.Text + "%")

                     select emp ).Distinct();

ex3:
var query=from emp in dc.Emps
   
                     where SqlMethods.Like(emp.ename, "%siva%")

                     select emp;




2 comments:

  1. sir please upload some demo,, with your post!

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete