【问题标题】:Override sql default value on insert using Entity Framework Core (7)使用 Entity Framework Core (7) 在插入时覆盖 sql 默认值
【发布时间】:2026-02-06 14:45:01
【问题描述】:

我有一个表,其中有一列 [CreatedAtIsoUtc] 设置了 Sql Server 默认值

migrationBuilder.CreateTable(
            name: "CurrentAccountLedger",
            columns: table => new
            {
                Id = table.Column<Guid>(nullable: false, defaultValueSql: "newsequentialid()"),
                CreatedAtIsoUtc = table.Column<DateTime>(nullable: false, defaultValueSql: "GETUTCDATE()"),                    
            }

        });

在原始 sql server 查询中,我可以插入一条记录并覆盖 [CreatedAtIsoUtc] 默认值。

在实体框架中,执行 Add() 操作时,我似乎无法覆盖此值。

关于如何让这个工作的任何想法?

【问题讨论】:

    标签: entity-framework entity-framework-core


    【解决方案1】:

    您可以使用HasDefaultValueSql() 在上下文的OnModelCreating() 中为您的实体设置原始SQL 默认值:

    class YourContext : DbContext
    {
        public DbSet<CurrentAccountLedger> CurrentAccountLedgers { get; set; }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<CurrentAccountLedger>()
                .Property(x => x.CreatedAtIsoUtc)
                .HasDefaultValueSql("GETUTCDATE()");
        }
    }
    

    【讨论】:

      【解决方案2】:

      实际上,在 EF Core v1.1.0 中,您可以通过将属性设置为任何类型的默认值不同来做到这一点(即,0 用于数字,false 用于 bool , null 用于 string 和可为空的类型,default(DateTime) 在你的情况下)。当前唯一的限制是您不能使用0falsenull 等覆盖 sql 默认值。

      例如

      db.CurrentAccountLedger.Add(new CurrentAccountLedger { });
      

      将插入一条CreatedAtIsoUtc等于默认GETUTCDATE()的记录,而

      db.CurrentAccountLedger.Add(new CurrentAccountLedger { CreatedAtIsoUtc = new DateTime(2017, 1, 1) });
      

      将插入具有指定值的记录。

      【讨论】:

      • 谢谢。我最初尝试过这个,但由于某种原因它不起作用。只需重新运行即可。不知道我在哪里搞砸了。
      • 这是否意味着无法将 EfCore 空值插入到具有默认值的可空列中:*.com/questions/41969303/…
      • @Boris Indeed(null 用于字符串和可为空的类型
      最近更新 更多