当前位置: 首页 > 编程语言 > C#

C#GenericDateTime.ToString()withCustomFormat分享

时间:2023-04-11 12:13:23 C#

C#GenericDateTime.ToString()withCustomFormat使用时:DateTime.ToString().Contains("2016")entity框架产生:CAST(DateValueASnvarchar(max))LIKE'%2016%'这使用默认日期格式“monddyyyyhh:miAM(或PM)”我想使用“yyyy-mm-ddhh:mi:ss(24h)”,这可以通过以下方式获得:CONVERT(VARCHAR(max),DateValue,20)LIKE'%2016%'我需要帮助将这种格式实现到现有的泛型方法中。staticExpressionExpr(Expressionsource){返回源;}staticMethodInfoGetMethod(thisLambdaExpressionsource){return((MethodCallExpression)source.Body).Method;}staticreadonlyMethodInfoObject_ToString=Expr((objectx)=>x.ToString()).GetMethod();staticreadonlyMethodInfoString_Contains=Expr((stringx)=>x.Contains("y")).GetMethod();publicstaticIQueryableFilter(thisIQueryablequery,Listfilters)whereT:BaseEntity{if(filters!=null&&filters.Count>0&&!filters.Any(f=>string.IsNullOrEmpty(f.Filter))){varitem=Expression.Parameter(query.ElementType,"item");varbody=filters.Select(f=>{varvalue=f.Column.Split('.').Aggregate((Expression)item,Expression.PropertyOrField);if(value.Type!=typeof(string)){value=Expression.Call(value,Object_ToString);}返回(Expression)Expression.Call(value,String_Contains,Expression.Constant(f.Filter));}).Where(r=>r!=null).Aggregate(Expression.AndAlso);varpredicate=Expression.Lambda(body,item);MethodInfowhereCall=(typeof(Queryable).GetMethods().First(mi=>mi.Name=="Where"&&mi.GetParameters().Length==2).MakeGenericMethod(query.ElementType));MethodCallExpressioncall=Expression.Call(whereCall,newExpression[]{query.Expression,predicate});query=query.Provider.CreateQuery(call);}返回查询;请注意,这是一个示例-它并不总是“2016”,它并不总是用户可以输入时间的年份,或者“01”以调用该月1日、1月或2001年的所有记录。这是一个非常灵活的过滤器。我也明白很多人不会喜欢这种情况,但我真的在这里寻找解决方案而不是被告知“不要这样做”解决方案也需要满足LINQtoEntities,所以我不能简单地.ToString("MMMdyyyyH:mmtt")因为这会导致:“LINQtoEntities无法识别方法'System.StringToString(System.String)'方法,并且此方法无法转换为存储表达。”该代码使用默认的日期格式。我的问题的原因是通过在EntityFramework中操作查询来更改SQL级别的日期格式。我发现产生所需结果的唯一方法是使用像这样的表达式手动构建它Expression>Date_ToString=date=>DbFunctions.Right("000"+date.Year.ToString(),4)+"-"+Db函数。Right("0"+date.Month.ToString(),2)+"-"+DbFunctions.Right("0"+date.Day.ToString(),2)+""+DbFunctions.Right("0"+date.Hour.ToString(),2)+":"+DbFunctions.Right("0"+date.Minute.ToString(),2)+":"+DbFunctions.Right("0"+date.Second.ToString(),2);丑,我知道。坦率地说,您不希望看到EF从上面的表达式生成的SQL-与预期的CONVERT(...)相比,它是一个巨大的怪物。但至少它有效。这是代码。上面的表达式可以使用System.Linq.Expressions构建,但我太懒了,使用了一个简单的参数替换器。修改部分:if(value.Type!=typeof(string)){if(value.Type==typeof(DateTime))value=value.ToDateString();否则如果(value.Type==typeof(DateTime?))value=Expression.Condition(Expression.NotEqual(value,Expression.Constant(null,typeof(DateTime?))),Expression.Property(value,“Value”).ToDateString(),Expression.Constant(""));否则value=Expression.Call(value,Object_ToString);}和使用过的助手:staticreadonlyExpression>Date_ToString=date=>DbFunctions.Right("000"+date.Year.ToString(),4)+"-"+DbFunctions.Right("0"+date.Month.ToString(),2)+"-"+DbFunctions.Right("0"+date.Day.ToString(),2)+""+DbFunctions.Right("0"+date.Hour.ToString(),2)+":"+DbFunctions.Right("0"+date.Minute.ToString(),2)+":"+DbFunctions.Right("0"+date.Second.ToString(),2);静态表达式ToDateString(此表达式源){returnDate_ToString.ReplaceParameter(源);}staticExpressionReplaceParameter(这个LambdaExpressionex表达式,表达式目标){returnnewParameterReplacer{Source=expression.Parameters[0],Target=target}.Visit(expression.Body);}classParameterReplacer:ExpressionVisitor{publicParameterExpressionSource;公共表达目标;protectedoverrideExpressionVisitParameter(ParameterExpressionnode){returnnode==Source?目标:base.VisitParameter(节点);如果你想确定日期是否在输入值的年份之内,为什么不呢:DateTime.Year==2016//或者你的变量也许你有比我看到的更多的需求。以上是C#学习教程:C#GenericDateTime.ToString()withcustomformat。多多关注——本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:

最新推荐
猜你喜欢