2017-01-16 210 views
0

我有一个柱[CreatedAtIsoUtc]的表中设置一个SQL Server的默认值覆盖SQL默认值(7)

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]默认值。

在Entity Framework中,执行Add()操作时似乎无法覆盖此值。

关于如何让这项工作有任何想法?

回答

3

其实在EF核心V1.1.0你可以做,通过属性设置为任意值不同比(即0代表数字,false代表bool,null代表string和可空类型,default(DateTime)代表您的情况)。目前唯一的限制是不能覆盖使用0的SQL默认值,falsenull

例如

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

会插入与CreatedAtIsoUtc记录等于默认GETUTCDATE(),而

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

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

+0

谢谢。我最初试过这个,但由于某种原因它不工作。刚刚重新运行,它的工作原理。不知道我在哪里搞砸了。 –

+0

这是否意味着使用EfCore null值不能插入到具有默认值的可空列中: http://stackoverflow.com/questions/41969303/ef-core-insert-null-value-to-nullable-column- that-has-default-value – borisdj

+0

@Boris的确(字符串和**为可空类型**为null) –

1

您可以在上下文的OnModelCreating()使用HasDefaultValueSql()在设置你的实体原始的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()"); 
    } 
}