Sunday, January 31, 2010

‘Like’ operator in Linq to Entities

Let’s say you have a query like the following

select * from product where lower(name) like 'computer%'

If you want to do the same thing in the Linq to Entities query, it is little tricky (at least for me :))

There is no operator by name 'like’ so we will have to make use of Contains, StartsWith, EndsWith keywords.

Here is goes…

public List<Product> GetProductsByName(string productName)
{
    var productQuery = context.Products.Where(p => p.Name.ToLower().StartsWith(productName));

    return productQuery.ToList();
}

Namaskara,

Harsha

1 comment:

  1. How about this:

    var productQuery =
    context.Products.Where(p => p.Name.Containts(productName));

    Just a sharing. Have a nice day. ^^
    from: http://oysterleelife.blogspot.com/

    ReplyDelete