简体   繁体   中英

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

How do I write this query in Linq to Entities:

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

Column Data is of varchar(max) type. 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.

Update :

I need to return the result of the L2E query as IQueryable, because paging / sorting is applied on top of it. This is another reason, why I want this field returned as DateTime - to be able to sort on it.

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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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