代码之家  ›  专栏  ›  技术社区  ›  Lost

如何为EFCore Postgres种子utcnow()

  •  0
  • Lost  · 技术社区  · 3 年前

    我正在尝试为 DateTime EF Core中的属性。目前正在播种 DateTime.Now 具有以下代码

    modelBuilder.Entity<AnalysisFile>()
                    .Property(analysisFile => analysisFile.TimeCreated)
                    .HasDefaultValueSql("now()");
    

    所以 now() 基本上是一个原生的Postgres方法,它在这里发挥了神奇的作用。我在网上搜索了一下,还查看了Postgres文档,看看是否有一个函数能给我带来这样的东西 utcnow() .

    https://www.postgresql.org/docs/current/functions-datetime.html

    我找不到这样的东西。也许Postgres中不存在该功能。然后我开始怀疑是否有任何方法可以将时区与`HasDefaultValueSql一起指定。我在那里也没有找到太多帮助。

    我是不是遗漏了什么?我认为这很简单,但我在EF Core或Postgres中找不到任何本地功能。有什么建议吗?

    0 回复  |  直到 3 年前
        1
  •  1
  •   granadaCoder    3 年前

    我创建了一个常量文件。

    public static class SqlKeyWords
    {
        public const string CurrentUserDefault = "CURRENT_USER"; /* SqlServer, PostGres */
    
        //public const string CurrentTimeStamp = "GETUTCDATE()"; /* SqlServer */
    
        public const string CurrentTimeStamp = "timezone('utc', now())"; /* PostGres */ 
    }
    

    然后我指的是 single source of truth 在我的“地图”中:

    using System.Diagnostics.CodeAnalysis;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Metadata.Builders;
    
    namespace MyCompany.MyEfLayer.OrmMaps
    {
        [ExcludeFromCodeCoverage]
        public class MyThingMap : IEntityTypeConfiguration<MyThingEntity>
        {
            public void Configure(EntityTypeBuilder<MyThingEntity> builder)
            {
    
    
                builder.Property(cn => cn.LastUpdated).HasColumnName("LastUpdatedColumn");
                builder.Property(dvsql => dvsql.LastUpdated).HasDefaultValueSql(SqlKeyWords.CurrentTimeStamp);
                builder.Property(req => req.LastUpdated).IsRequired();
    
            }
        }
    }