2011-03-20 83 views
17

我有以下查询:实体框架4/Linq:如何将DateTime转换为查询中的字符串?

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是字符串。

任何想法?这必须是一个微不足道的问题。

回答

19

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

最简单的将是第一个项目在查询中匿名类型,然后使用AsEnumerable()强制转换为IEnumerable - 之后,你可以因为你现在使用LINQ为查询表达式的其余对象使用ToString()(有关于此主题的冗长的文章here)。

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

太棒了。我刚刚使用了我的POCO,然后在最后一分钟使用了.AsEnumerable()。选择(p ...并且它运行得非常好。 – 2011-03-21 02:18:16

+1

“关于此主题的冗长文章”链接似乎已被打破。:-( – 2015-05-22 18:25:42

+0

@BrokednGlass好的答案。谢谢 – User 2015-06-08 09:59:00

34

这里有一个选择:

.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()结果。

+1

这很好!我需要这样做以保持我的原始对象IQueryable。谢谢! – duyn9uyen 2013-07-17 16:23:06

+0

简单,没有转换为首先是可枚举的 – brian 2013-10-30 08:24:21

+0

这是一个非常有用的答案。谢谢:-) – 2014-04-04 08:03:29

0

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

编辑(1/23/08):由此生成的SQL在6.0.2和6.1.3之间更改。最初,如果值为null,则生成的SQL将创建一个空结果。在这种情况下,我认为这是可取的,但我可以看到为什么在其他情况下它不会被期望(null +“一个字符串值”= null),并且可能导致输出不等于您希望的值。我将详细介绍列输出如何在下面进行更改,但蹭它是现在这将输出空值“//::”。我只是在我的调用代码中处理这个输出作为特例,并手动将其更改为null,但其他人可能想要解决添加更强大的结果以确保空值输出为空。还值得注意的是,新版本中的SQL语句非常长。

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之,改变你这样的代码:

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); 
0

这种结构(我假设的数据类型为DATETIME)创建一个新的POCO

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

,请注意我使用UserProductVM代替ProductVMSetModified改为修改

然后,当你得到修改属性,新的POCO是要去把它作为你格式化字符串。