Linq Expression Builder datetime.year compare

dynamic-linq entity-framework expression-trees linq

Question

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.

1
0
10/14/2014 3:57:33 PM

Accepted Answer

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.

0
10/9/2018 8:34:18 PM

Popular Answer

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



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