【问题标题】:Entity Framework 4 / Linq: How to convert from DateTime to string in a query?Entity Framework 4 / Linq:如何在查询中将 DateTime 转换为字符串?
【发布时间】:2011-03-20 18:11:57
【问题描述】:

我有以下疑问:

from a in Products
select new ProductVM
    {
         id = a.id,
         modified = a.modified.ToString()
    }

这给了我一个错误:

LINQ to Entities does not recognize the method 'System.String ToString()'
method, and this method cannot be translated into a store expression.

产品表中的modified 是日期时间。 ProductVM 类中的modified 是字符串。

有什么想法吗?这一定是个小问题。

【问题讨论】:

    标签: entity-framework-4 linq-to-entities tostring


    【解决方案1】:

    这里有一个替代方案:

    .Select( p -> SqlFunctions.StringConvert((double)
                      SqlFunctions.DatePart("m", p.modified)).Trim() + "/" +
                  // SqlFunctions.DateName("mm", p.modified) + "/" + MS ERROR?
                  SqlFunctions.DateName("dd", p.modified) + "/" +
                  SqlFunctions.DateName("yyyy", p.modified)
    

    显然DateName("MM", ..) 拼出了月份名称,其中DatePart("mm", ..) 提供了一个数值,因此StringConvert( ),但是这个左边用空格填充了结果,因此.Trim()。

    【讨论】:

    • 简单且不强制转换为可枚举优先
    • 真的很棒。是否可以将此方法放在表达式树中并重用它?谢谢!
    • SqlFunctions.DateName("dd", p.modified) 似乎没有返回格式化的两位数字。我期望'01',但它返回'1'。非常令人失望。
    • SqlFunctioins.StringConvert() 有第二个参数指定转换后的字符串的长度。默认值为 10,它向左填充空格。 (我很想指定 2 并用零填充!)这就是为什么需要 Trim()。
    • 谢谢! SqlFunctions.DateName("yyyy", value) + "" + SqlFunctions.DateName("m", value) + "" + SqlFunctions.DateName("d", value) + "" + SqlFunctions.DateName("hh", value) + "" + SqlFunctions.DateName("n", value) + "" + SqlFunctions.DateName("s", value) + "" + SqlFunctions.DateName("ms", value)
    【解决方案2】:

    Linq to Entities 不支持ToString() - SqlFunctions 中有一个函数助手列表,但这不支持日期到字符串的转换。

    最简单的方法是首先在查询中投影到匿名类型,然后使用 AsEnumerable() 转换为 IEnumerable - 之后您可以使用 ToString(),因为您现在使用 Linq to Objects查询表达式(关于这个主题有一篇很长的文章here)。

       var results = Products.Select( p => new { a.id, a.modified })
                             .AsEnumerable()
                             .Select(p => new ProductVM() 
                                    { id = p.id, 
                                      modified = p.modified.ToString() 
                                    });
    

    【讨论】:

    • 太棒了。我之前只是使用了我的 POCO,然后在最后一分钟使用了 .AsEnumerable().Select(p ... 效果非常好。
    • “关于此主题的冗长文章”链接似乎已损坏。 :-(
    • @BrokednGlass 不错的答案。谢谢
    • 这种方法很简单,但我不会说它适用于现实生活场景,因为这将遍历整个Products 表。它在哪里是原始查询中的Where 子句需要过滤日期值(转换为字符串),结果 SQL 查询会更糟。
    【解决方案3】:

    用这个结构新建一个POCO(我假设数据类型是DateTime):

    public class UserProductVM {
        ...
        private DateTime _modified;
    
        public DateTime SetModified { set { _dateEvent = value; } }
        public string Modified { get { return _modified.ToString("dd MMM yyyy @ HH:mm:ss"); } }
        ...
    }
    

    然后您将值分配给 SetModified,像这样更改您的代码:

    from a in Products
    select new UserProductVM
    {
         ...
         SetModified = a.modified
    }
    

    注意我使用的是 UserProductVM 而不是 ProductVM 和 SetModified 而不是 modified。

    然后当你得到属性Modified,新的POCO会把它作为你格式化的字符串。

    【讨论】:

      【解决方案4】:

      这可能不会增加很多,但以防万一有人像我一样疯狂,如果您需要使用 DatePart/DateName 为 Zim 博士的答案构建表达式树,这里是完整的代码,包括时间部分。显然,出于其他目的,您可以更改 Product->YourInitialType、ProductVM->YourResultType 和 modified->YourProperty。

      编辑(2008 年 1 月 23 日):由此生成的 SQL 在 6.0.2 和 6.1.3 之间发生了变化。最初,如果值为空,则生成的 SQL 将创建空结果。在这种情况下,我认为这是可取的,但我可以理解为什么在其他情况下不需要它(null +“a string value”=null)并且可能导致输出不等于您想要的。我将在下面详细说明列输出是如何变化的,但问题是现在它将为空值输出“// ::”。我只是在我的调用代码中将此输出作为一种特殊情况处理并手动将其更改回 null,但其他人可能想要解决添加更强大的结果以确保 null 输出为 null。另外值得注意的是,新版本的SQL语句很长。

      ParameterExpression paramExp = Expression.Parameter(typeof(Product));
      string propertyName = "modified";            
      Expression propertyOrField = Expression.PropertyOrField(paramExp, propertyName);
      
      MethodInfo datePartMethod = typeof(System.Data.Entity.SqlServer.SqlFunctions).GetMethods().Where(x => x.Name == "DatePart" && x.GetParameters().Length == 2 && x.GetParameters()[1].ParameterType == typeof(DateTime?)).First();
      MethodInfo dateNameMethod = typeof(System.Data.Entity.SqlServer.SqlFunctions).GetMethods().Where(x => x.Name == "DateName" && x.GetParameters().Length == 2 && x.GetParameters()[1].ParameterType == typeof(DateTime?)).First();
      MethodInfo stringConvertMethod = typeof(System.Data.Entity.SqlServer.SqlFunctions).GetMethods().Where(x => x.Name == "StringConvert" && x.GetParameters().Length == 1 && x.GetParameters()[0].ParameterType == typeof(decimal?)).First();
      MethodInfo stringConcatMethod = typeof(string).GetMethods().Where(x => x.Name == "Concat" && x.GetParameters().Length == 2 && x.GetParameters()[0].ParameterType == typeof(string) && x.GetParameters()[1].ParameterType == typeof(string)).First();
      MethodInfo stringTrimMethod = typeof(string).GetMethods().Where(x => x.Name == "Trim" && x.GetParameters().Length == 0).First();
      Type projectedType = typeof(ProductVM);
      NewExpression newHolder = Expression.New(projectedType);  
      MemberInfo member = anonType.GetMember("modified")[0];
      var monthPartExpression = Expression.Call(null, datePartMethod, Expression.Constant("mm", typeof(string)), propertyOrField);
      var convertedMonthPartExpression = Expression.Call(null, stringConvertMethod, Expression.Convert(monthPartExpression, typeof(decimal?)));
      var convertedDayPartExpression = Expression.Call(null, dateNameMethod, Expression.Constant("dd", typeof(string)), propertyOrField);
      var convertedYearPartExpression = Expression.Call(null, dateNameMethod, Expression.Constant("yyyy", typeof(string)), propertyOrField);
      var convertedHourPartExpression = Expression.Call(null, dateNameMethod, Expression.Constant("hh", typeof(string)), propertyOrField);
      var convertedMinutePartExpression = Expression.Call(null, dateNameMethod, Expression.Constant("n", typeof(string)), propertyOrField);
      var convertedSecondPartExpression = Expression.Call(null, dateNameMethod, Expression.Constant("ss", typeof(string)), propertyOrField);
      
      var allAddedExpression = Expression.Call(null, stringConcatMethod, 
                  convertedMonthPartExpression, 
                  Expression.Call(null, stringConcatMethod,
                      Expression.Constant("/", typeof(string)), 
                      Expression.Call(null, stringConcatMethod, 
                          convertedDayPartExpression, 
                          Expression.Call(null, stringConcatMethod, 
                              Expression.Constant("/", typeof(string)), 
                              Expression.Call(null, stringConcatMethod,
                                  convertedYearPartExpression,
                                  Expression.Call(null, stringConcatMethod,
                                      Expression.Constant(" ", typeof(string)),
                                      Expression.Call(null, stringConcatMethod,
                                          convertedHourPartExpression,
                                          Expression.Call(null, stringConcatMethod,
                                              Expression.Constant(":", typeof(string)),
                                              Expression.Call(null, stringConcatMethod,
                                                  convertedMinutePartExpression,
                                                  Expression.Call(null, stringConcatMethod,
                                                      Expression.Constant(":", typeof(string)),
                                                      convertedSecondPartExpression
      
      ))))))))));
      var trimmedExpression = Expression.Call(allAddedExpression, stringTrimMethod, new Expression[] { });    
      var month = Expression.Bind(member, trimmedExpression);
      
      MemberInitExpression memberInitExpression =
          Expression.MemberInit(
              newHolder,
              new MemberBinding[] { month });
      var lambda = Expression.Lambda<Func<Product, ProductVM>>(memberInitExpression, paramExp);
      

      【讨论】:

        猜你喜欢
        • 2021-10-14
        • 2022-01-06
        • 2021-05-09
        • 2011-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-13
        相关资源
        最近更新 更多