I am writing a small console and I want the user to specify a field and a value to search for. Unfortunately, I can’t seem to specify the field name in my linq to Sql query. It should be possible, as the list of fields do exist somewhere. Rather than try to explain it, here’s what I would like to do:
...
if (!String.IsNullOrEmpty(filterCriteria.OrderNumberEnd)) query = from o in query where o.orderDate <= filterCriteria.OrderDateEnd select o;
if (!String.IsNullOrEmpty(filterCriteria.OrderNumberStart)) query = from o in query where o.orderDate >= filterCriteria.OrderDateStart select o;
if (!String.IsNullOrEmpty(filterCriteria.Keyword) && !String.IsNullOrEmpty(filterCriteria.Field))
query = query.Where(String.Format("{0}={1}", filterCriteria.Keyword, filterCriteria.Field);
The last line is doesn’t work, can it work or is this a limitation to linq to sql?
You will need dynamic LINQ in order to accomplish that. It does not come out of the box.
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
http://blog.bvsoftware.com/post/2008/02/27/How-to-create-a-Dynamic-LINQ-Query-Programmatically.aspx