简体   繁体   English

如何在L2E查询中表示t-sql convert(datetime,data,style)?

[英]How to represent t-sql convert(datetime,data,style) in L2E query?

How do I write this query in Linq to Entities: 如何在Linq to Entities中编写此查询:

select convert(datetime,data,103) from Audit where ActionId = 1

Column Data is of varchar(max) type. 列数据是varchar(max)类型。 I know that if the ActionId equals one in a row, than the Data column in the row will always contain a string that represents a date in dd/MM/yyyy format. 我知道,如果ActionId连续等于1,则该行的Data列将始终包含一个以dd / MM / yyyy格式表示日期的字符串。

Update : 更新

I need to return the result of the L2E query as IQueryable, because paging / sorting is applied on top of it. 我需要将L2E查询的结果返回为IQueryable,因为在它之上应用了分页/排序。 This is another reason, why I want this field returned as DateTime - to be able to sort on it. 这是另一个原因,为什么我希望将此字段作为DateTime返回-能够对其进行排序。

Would it be easier to format on client instead of server? 在客户端而不是在服务器上进行格式化会更容易吗?

I would do something like this: 我会做这样的事情:

var audits = db.Audit
    .Where(arg => arg.ActionId == 1)
    .Select(arg => new { arg.Data })
    .AsEnumerable()
    .Select(arg => DateTime.ParseExact(arg.Data, "dd/MM/yyyy", CultureInfo.InvariantCulture)
    .ToList();

The data will be retrieved in string format. 数据将以字符串格式检索。
After strings are retrieved they will be converted to DateTime . 检索到字符串后,它们将被转换为DateTime

I've found this: Convert String to Int in EF 4.0 It looks, like this trick might help, if we create a function to cast string into datetime. 我发现了这一点: 在EF 4.0中将字符串转换为Int ,如果我们创建一个将字符串转换为日期时间的函数,则看起来像这样的技巧可能有所帮助。

UPDATE This problem left unsolved for me. 更新此问题对我来说还没有解决。 As I needed a quick solution I converted the 'data' column to be of datetime type. 由于需要快速解决方案,因此将“数据”列转换为日期时间类型。 This is not generic for future extensions, but it works for now. 对于将来的扩展,这不是通用的,但现在可以使用。 One of the solutions that are not really a solution. 解决方案之一不是真正的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM