实体框架4 / Linq:如何在查询中将DateTime转换为字符串? [英] Entity Framework 4 / Linq: How to convert from DateTime to string in a query?

查看:107
本文介绍了实体框架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.

产品表中的修改是DateTime 。
ProductVM类中的修改是字符串。

The modified in the Products table is DateTime. The modified in the ProductVM class is string.

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

Any ideas? This has to be a trivial issue.

推荐答案

ToString()在Linq to Entities中不支持 - 作为 SqlFunctions ,但这不支持Date转换字符串。

ToString() is not supported in Linq to Entities - there is a list of function helpers as part of SqlFunctions but this doesn't support Date to string conversion.

最简单的方法是首先在查询中投射到匿名类型,然后转换为 IEnumerable 通过使用 AsEnumerable() - 之后,您可以使用 ToString(),因为您现在正在使用Linq to Objects查询表达式的其余部分(有关于此主题的冗长文章此处)。

Easiest would be to first project to an anonymous type within the query and then cast to an IEnumerable by using AsEnumerable() - after that you can use ToString() because you are now using Linq to Objects for the remainder of the query expression (there's a lengthy article on this topic here).

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

这篇关于实体框架4 / Linq:如何在查询中将DateTime转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆