In this blog you will find ASP.NET 3.5 articles and some code samples. These code samples are created by me and should be working. Thanks for visiting my blog! Happy Dot Netting

Wednesday, January 14, 2009

LINQ to SQL - Performing LIKE SQL queries

This blog would teach you to perform the equivalent of a LIKE Select with LINQ to SQL in several ways. 
First, you can use String methods such as Length, Substring, Contains, StartsWith, EndsWith, IndexOf, Insert, Remove, Replace, Trim, ToLower, ToUpper, LastIndexOf, PadRight, and PadLeft with LINQ to SQL queries
Alternatively, more flexible way to make LIKE queries is to use the System.Data.Linq.SqlClient.SqlMethods.Like() method.

This blog is an extension of my previous blog**. I have added five queries here which would give to insight about how to perform LIKE queries. Description of query is mentioned right above each query

  
protected void Page_Load(object sender, EventArgs e)
    {
        // ***Performing Like queries***
        // Query all rows where name starts with A
        //var query = db1.Products.Where(p => p.Name.StartsWith("A"));
        // Query all rows where name ends with p
        //var query = db1.Products.Where(p => p.Name.EndsWith("p"));
        // Query all rows where name contains p
        //var query = db1.Products.Where(p => p.Name.Contains("p"));
        // Query all rows where name lenght is 10
        //var query = db1.Products.Where(p => p.Name.Length == 10);

        // Query with SQL like method - This is more flexible as you can as many wildcards patterns as you need
        // For using Like method you would need to add System.Data.Linq.SqlClient;
        var query = db1.Products.Where(p => SqlMethods.Like(p.Name,"A%"));

        
        GridView1.DataSource = query;
        GridView1.DataBind();
    }

**Last blog Link http://myaspdotnet35.blogspot.com/2009/01/linq-to-sql-select-example.html
This will guide you how to prepare for this blog.
 



No comments: