使用实体框架核心 (7) 在插入时重写 sql 默认值



我有一个表,其中有一列[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 服务器查询中,我可以插入记录并覆盖 [CreatedAtIsoUtc] 默认值。

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

关于我如何让它工作的任何想法?

实际上在

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

例如

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

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

db.CurrentAccountLedger.Add(new CurrentAccountLedger { CreatedAtIsoUtc = new DateTime(2017, 1, 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()");
    }
}

最新更新