CameronR
CameronR

Reputation: 9

How to search a database using properties of model

I have an MVC4 program in which I have a dropdown with a list of all of the properties of a model. I want the user to be able to select which property then type in a string value to the textbox to search. The issue is I can't dynamically change the query with the value of the dropdown.

public ActionResult SearchIndex(string searchString, string searchFields)
    {
        var selectListItems = new List<SelectListItem>();
        var first = db.BloodStored.First();
        foreach(var item in first.GetType().GetProperties())
        {
            selectListItems.Add(new SelectListItem(){ Text = item.Name, Value = item.Name});
        }
        IEnumerable<SelectListItem> enumSelectList = selectListItems;
        ViewBag.SearchFields = enumSelectList;

        var bloodSearch = from m in db.BloodStored
                          select m;

        if (!String.IsNullOrEmpty(searchString))
        {
            PropertyInfo selectedSearchField = getType(searchFields);
            string fieldName = selectedSearchField.Name;

            //Dynamic Linq query this is how it needs to be set up to pass through linq.dynamic without exception
            bloodSearch = bloodSearch.Where("x => x." + fieldName + " == " + "@0", searchString).OrderBy("x => x." + fieldName);
            return View(bloodSearch); 
        }
        return View(bloodSearch);
    }

Here is my getType method

public PropertyInfo getType(string searchFields)
    {
        var first = db.BloodStored.First();
        foreach (var item in first.GetType().GetProperties())
        {
            if(searchFields == item.Name)
            {
                return item;
            }
        }
        return null;
    }

I have updated my code to reflect the working query encase it can help anyone else out. Here is a link to the post that I found my answer from Dynamic query with LINQ won't work

Upvotes: 0

Views: 99

Answers (2)

jfin3204
jfin3204

Reputation: 709

you could build the expression yourself.

static Expression<Func<T, bool>> GetExpression<T>(string propertyName, string propertyValue)
{
    var parameterExp = Expression.Parameter(typeof(T), "type");
    var propertyExp = Expression.Property(parameterExp, propertyName);
    MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
    var someValue = Expression.Constant(propertyValue, typeof(string));
    var containsMethodExp = Expression.Call(propertyExp, method, someValue);

    return Expression.Lambda<Func<T, bool>>(containsMethodExp, parameterExp);
}

stole this from a post by Marc Gravell.

Upvotes: 0

Bozman
Bozman

Reputation: 477

you should use the Dynamic.cs library. you can find it here as well as examples. You can then create your where clauses dynamically.

dynamic.cs

Upvotes: 1

Related Questions