Using Dynamic Linq and the entity frame work I have the below code:
private void ComboBox_DropDown(object sender, EventArgs e)
{
ComboBox cb1 = (ComboBox)sender;
string SelectField = cb1.Name.Substring(2);
var query = MyContext.Items.Select(SelectField);
foreach (ComboBox cb2 in gbFilters.Controls.OfType<ComboBox>().Where(com => com.Text != ""))
{
string propertyName = cb2.Name.Substring(2);
string propertyValue = cb2.Text;
query = query.Where(propertyName + "=@0", propertyValue);
}
var x = query;
x = x.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Distinct",
new Type[] { x.ElementType },
x.Expression));
foreach (var y in x)
{
if (y != null)
cb1.Items.Add(y.ToString());
}
}
The main focus being the foreach portion. Everything else seems to work fine. But when I do have another dropdown that has a value I get an error. "No property or field 'Color' exists in type 'String'" and Color can be replaced with any ComboBox name.
So in the example above if ComboBox cbColor
has the Text White
and I perform a dropdown on ComboBox 'cbType' the above code would become the same as:
var query = MyContext.Items.Select("Type");
query = query.Where("Color=@0", "White");
and I get the error "No property or field 'Color' exists in type 'String'"
You are doing the steps in the wrong order. Each part of the query is done in the order applied. First you are narrowing it to your list of strings, then applying the where filters to the list of strings, apply your select last instead of first.