17 Apr 2013

Linq "Sounds Like" queries on SQL using SoundEx / SoundCode

Using .NET 4 and Entity Framework it's quite easy to add "sounds like" query functionality using SQL's underlying SOUNDEX function.

The key is to use the SqlFunctions object found in System.Data.Objects.SqlClient, e.g.


var query = dataContext.Agencies.AsQueryable();

if (!string.IsNullOrEmpty(searchTerm))
{
   query = query.Where(agency => agency.Name.Contains(searchTerm) || SqlFunctions.SoundCode(agency.Name) == SqlFunctions.SoundCode(searchTerm));
}

3 comments:

  1. Thanks for this James. Any idea how to sort the results by relevance in this case?

    ReplyDelete
  2. Would like to know how to Sort or Order By weight.

    ReplyDelete

Comments are very welcome unless you're a spammer, in which case you should probably kill yourself.

If I helped you out today, you can buy me a beer below. Cheers!