What do you call the cast() function of the database in the ORDER method of a database in a LINQ expression in C# C#?

Asked

Viewed 46 times

1

I have a field that stores DATETIME in my database. However I need to ignore the time of this field when I am ordering for it. The following code makes my search:

public virtual async Task<(List<TModel>, int)> FindAsync(IQueryable<TModel> query, int pageNumber = 1, int pageSize = 20, string[] sortExpression = null, Expression<Func<TModel, object>> includes = null)
    {
        query = Includes(includes, query);
        query = SetFilterAll(query);

        var count = await query.CountAsync();
        query = Sort(sortExpression, query);
        query = Pagination(pageNumber, pageSize, query);
        return (await query.ToListAsync(), count);
    }

I would like to send in the parameter sortExpresion something like, CAST(meu_campo_date AS DATE) So that in the end it would execute an SQL similar to this:

SELECT * FROM MinhaTabela ORDER BY CAST(meu_campo_date AS DATE) DESC

1 answer

1

You can use the property Datetime.Date. See the example below:

using System;

public class Program
{
    public static void Main()
    {
        var dateTime = DateTime.Now;
        Console.WriteLine("Isto irá imprimir a data e hora: {dateTime}");
        Console.WriteLine("Isto irá imprimir apenas a data: {dateTime.Date}");
    }
}

See this example in . NET Fiddle: https://dotnetfiddle.net/jixgMY

  • In that case you don’t answer me, Keven. I need that there is time that ORDER BY will execute my SQL query to use only the date. The critical point is that I need to do this through the entityframework sending by the extension method of the Iqueryable interface.

  • How did you not put the method sort i have no way of knowing exactly how the ordering was implemented, but it would be something like query.OrderBy(x => x.SuaPropriedadeData.Date). In this way the Entityframework itself would mount the ordering of the query.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.