How to compare only date components from DateTime in EF?

后端 未结 14 1031
野性不改
野性不改 2020-11-27 17:06

I am having two date values, one already stored in the database and the other selected by the user using DatePicker. The use case is to search for a particular date from the

14条回答
  •  无人及你
    2020-11-27 17:11

    I think this could help you.

    I made an extension since I have to compare dates in repositories filled with EF data and so .Date was not an option since it is not implemented in LinqToEntities translation.

    Here is the code:

            /// 
        /// Check if two dates are same
        /// 
        /// Type
        /// date field
        /// date compared
        /// bool
        public Expression> IsSameDate(Expression> valueSelector, DateTime value)
        {
            ParameterExpression p = valueSelector.Parameters.Single();
    
            var antes = Expression.GreaterThanOrEqual(valueSelector.Body, Expression.Constant(value.Date, typeof(DateTime)));
    
            var despues = Expression.LessThan(valueSelector.Body, Expression.Constant(value.AddDays(1).Date, typeof(DateTime)));
    
            Expression body = Expression.And(antes, despues);
    
            return Expression.Lambda>(body, p);
        }
    

    then you can use it in this way.

     var today = DateTime.Now;
     var todayPosts = from t in turnos.Where(IsSameDate(t => t.MyDate, today))
                                          select t);
    

提交回复
热议问题