question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Translate to PostgreSQL date_trunc

See original GitHub issue

date_trunc('week', now()::date

Looking to make a call similar to this, and can’t figure out what should be used now. I’ve also looked at EF.Property<DateTime>() but that doesn’t seem to help.

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:1
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

4reactions
rojicommented, Sep 4, 2020

The provider does translate certain expressions with date_trunc (e.g. DateTime.Date gets translated to date_trunc('day', ...), but there’s no general .NET method which is the equivalent of PostgreSQL date_trunc. We could add a translation for this under EF.Functions.

In the meantime you can map it via your own DbFunction mapping:

class Program
{
    static async Task Main(string[] args)
    {
        await using var ctx = new BlogContext();
        await ctx.Database.EnsureDeletedAsync();
        await ctx.Database.EnsureCreatedAsync();

        _ = ctx.Blogs.Where(b => BlogContext.DateTrunc("weeks", b.Creation) == new DateTime(2000, 1, 1)).ToList();
    }
}

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    static ILoggerFactory ContextLoggerFactory
        => LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseNpgsql(@"Host=localhost;Username=test;Password=test")
            .EnableSensitiveDataLogging()
            .UseLoggerFactory(ContextLoggerFactory);

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDbFunction(DateTruncMethod).HasName("date_trunc");
    }

    private static readonly MethodInfo DateTruncMethod
        = typeof(BlogContext).GetRuntimeMethod(nameof(DateTrunc), new[] { typeof(string), typeof(DateTime) });

    public static DateTime DateTrunc(string field, DateTime source)
        => throw new NotSupportedException();
}

public class Blog
{
    public int Id { get; set; }
    public DateTime Creation { get; set; }
}
3reactions
FossaMalaEntcommented, Oct 18, 2022

I’m using it on a “.GroupBy()” and it don’t work.

public class MyContext : DbContext
{
    public DbSet<MyEntity> MyEntities { get; set; }

    public MyContext (DbContextOptions<MyContext> options) : base(options) { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDbFunction(DateTruncMethod).HasName("date_trunc");

        modelBuilder.Entity<MyEntity>().ToTable("TableName");
    }
    
    private static readonly MethodInfo DateTruncMethod
        = typeof(MyContext).GetRuntimeMethod(nameof(DateTrunc), new[] { typeof(string), typeof(DateTime) });

    public static DateTime DateTrunc(string field, DateTime source)
        => throw new NotSupportedException();
}

LINQ

        var q = this_context.MyEntities.Where(x => x.mac.Equals("address"));
        var qualcosa = await q.GroupBy(x => MyContext.DateTrunc("minute", x.Created))
                                 .Select(x => new ResultDTO()
                                 {
                                     Date = x.Key.ToString(),
                                     Average = x.Average(y => y.Value)
                                 })
                                 .ToListAsync();

But i get

The LINQ expression ‘DbSet<MyEntity>() .Where(x => x.Mac.Equals(“address”)) .GroupBy(x => MyContext.DateTrunc(field: “hour”, source: x.Created))’ could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to ‘AsEnumerable’, ‘AsAsyncEnumerable’, ‘ToList’, or ‘ToListAsync’. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

It fails on the groupBy, I know cause I’ve tried commenting the Select and fails anyway, but if I comment also the groupBy then it works.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Documentation: 15: 9.9. Date/Time Functions and Operators
Subtract timestamps (converting 24-hour intervals into days, similarly to ... date_trunc ( text , timestamp with time zone , text ) → timestamp...
Read more >
Convert date over to PostgreSQL using Date_trunc
I have a date I am wanting to convert and I can't seem to switch it over to PostgreSQL format, I would like...
Read more >
PostgreSQL date_trunc Function By Examples
The date_trunc function truncates a TIMESTAMP or an INTERVAL value based on a specified date part e.g., hour, week, or month and returns...
Read more >
PostgreSQL to_date Function: Convert String to Date
This tutorial shows you how to use the PostgreSQL to_date function that allows you to convert a string literal to a date value...
Read more >
How to extract the date from a column in Postgres
We can extract the date from a timestamp column in the following ways: The DATE() method; The ::date suffix; The TO_CHAR() method; The...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found