Search code examples
c#entity-frameworklinq

How to create Linq Expression for DateTime.Date


How to create Linq Expression for DateTime.Date?

For example:

var query = CollectionQuery.OrderBy(c => c.CreatedAtUtc.Date); // where CollectionQuery is User type
var expressions = query.Expression;

When I debug I found expressions contain expression type Quote:

enter image description here

I want it to be dynamic so I use System.Linq.Expression (EF Core 2.2)

ParameterExpression arg = Expression.Parameter(typeof(User), "c");
var memberExpression = Expression.Property(arg, "CreatedAtUtc");
var quoteExpression = Expression.Quote(memberExpression); // no parameter to set .Date

My problem is I cannot create an expression with .Date - how can I do this? Thank you.


Solution

  • after @Jeremy Lakeman suggest

    ParameterExpression arg = Expression.Parameter(typeof(User), "c");
    var memberExpression = Expression.Property(Expression.Property(arg, "CreatedAtUtc"), "Date"); // add this line
    var labmdaExpression = Expression.Lambda<Func<T, DateTime>>(memberExpression, arg);
    var quoteExpression = Expression.Quote(labmdaExpression);
    

    when I look into quoteExpression on debug it will show

    enter image description here