0

Currently I am using expression builder for dynamic query generation.

I have created dynamic expressions for int, date time, and string operators. Now I am stuck at one point .

I want to compare month part of datetime through expression.

We are passing property of datetime and want to create expression for month of that property.

Code:

public static Expression GetDynamicquery<TSource>(
        string property, object value, ParameterExpression p)
    {

        var propertyReference = Expression.Property(p, property);


        var constantReference = Expression.Constant(value);
        var expression = Expression.Equal(propertyReference, constantReference);
        MethodInfo method = null;



                return Expression.LessThanOrEqual(propertyReference, constantReference);



    }

Here property is name of property which I am passing into Tsource.

p is parameter expression of type Tsource.

I want result like all birthdate of this month.

Celeo
  • 5,583
  • 8
  • 39
  • 41

2 Answers2

0

You can use Expression.PropertyOrField method for that. Not sure it would work with entity framework query though.

http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.propertyorfield(v=vs.110).aspx

Update

For entity framework you can use SqlFunctions.DatePart method.

http://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions(v=vs.110).aspx

You would need an Expression.Call to represent that as an expression.

http://msdn.microsoft.com/en-us/library/bb349020(v=vs.110).aspx

George Polevoy
  • 7,450
  • 3
  • 36
  • 61
0

I got answer of my question. What I did is like....

Code:

public static Expression GetDynamicquery<TSource>(
    string property, object value, ParameterExpression p)
{

    var propertyReference = Expression.Property(p, property);

    propertyReference = Expression.Property(propertyReference, "Year");

    var constantReference = Expression.Constant(value);
    return Expression.Equal(propertyReference, constantReference);
}

Here first property reference will give datetime expression.

And again using that expression we can go one step inside and can access year property. Same thing we can do for month.

Xiaoy312
  • 14,292
  • 1
  • 32
  • 44