Parsing string values to correct type in dynamic linq queries

dynamic dynamic-linq entity-framework linq

Question

I am trying to create a dynamic LINQ expression using the System.Linq.Dynamic assembly. I have a list of columns that I would like to search for a particular value that the user submits. E.g

If the user enters 5 into the search then it will search the columns specified for that value. My issue arises when I am comparing the search text which is always treated as a string to a column with a different type. All of the examples that I have read the type of the column is known before hand and the correct type is used, it seems that I need to be able to either parse the search string to the correct type or .ToString() the database value, however this then breaks for null. See below for a snippet of code:

public IEnumerable<Product> GetProducts(string searchText, List<string> searchFields)
{
    var products = dbSet.Where(p => !p.IsDisabled); //dbSet is a global variable linking to the products table

    foreach (var searchField in searchFields)
    {
        products = products.Where(searchField + ".ToString() == @0", searchText);
    }

    return products.OrderBy(p => p.ASPNo);
}

thanks in advance for any help/pointers in the right direction

1
1
11/14/2014 10:44:19 AM

Popular Answer

Have you tried checking the searchField for null before passing it to .ToString()
So do something like:

foreach (var searchField in searchFields)
{
    products = products.Where(searchField + " != null && " + searchField + ".ToString() == @0", searchText);
}
0
11/16/2014 4:47:00 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow