I have following situation:
public class BaseClass
{
public string Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
}
public class Product: BaseClass
{
/* Some methods*/
}
public class Country: BaseClass
{
/* Some methods*/
}
public class MyCustomClass
{
public Product Product { get; set; }
public Country Country { get; set; }
}
I want to create a list of expressions which I would later use to query my MyCustomClass
, example
var listOfExpressions= new List<Expression<Func<MyCustomClass, bool>>>();
if (x == 1)
listOfExpressions.Add(x => x.Product.Field1 == "Fruit")
/*.
.
.*/
if (y == 2)
listOfExpressions.Add(x => x.Country.Field2 == "Western")
}
Now this looks really ugly with these bunch of Ifs and I would prefer to have a method in BaseClass
for which you would pass int
({1,2,3}
) and it would return me the expression. The problem is that I need to have expression of type <MyCustomClass, bool>
but in my BaseClass
I can't directly get that, is there an way I could acheive this without complicating code too much?
I am thinking about something like this:
public class BaseClass
{
public string Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
protected Expression<Func<BaseClass, bool>> GetExpression(int key, string value)
{
switch (key)
{
case 1:
return x => x.Field1 == value;
case 2:
return x => x.Field2 == value;
case 3:
return x => x.Field3 == value;
}
}
By now I am stuck of how to get Expression<Func<BaseClass, bool>>
to be used in Expression<Func<MyCustomClass, bool>>
.
EDIT: The purpose of the expression:
I want to constuct a list of expressions to later use it to query database using Entity framework core. Example:
var query = DbContext.MyCustomClass.AsQueryable();
foreach (var expression in listOfExpressions)
{
query = query.Where(expression);
}