[英]How can I alter a model to set the SQL default date when using EF code migrations
Firstly, there are a lot of answers in this StackOverflow question that are of a similar ilk which helped me get very close, but none quite work in my situation.首先,在这个 StackOverflow 问题中有很多类似的答案帮助我非常接近,但在我的情况下没有一个完全有效。
I have a model class:我有一个 model class:
public class TestModel
{
[Key]
public int TestModelId { get; set; }
public DateTime CreatedOn { get; set; }
}
And this is added to a DbContext
file like so:并将其添加到DbContext
文件中,如下所示:
public virtual DbSet<TestModel> TestModels { get; set; }
So on add-migration
this produces:因此,在add-migration
时,这会产生:
...
migrationBuilder.CreateTable(
name: "TestModels",
columns: table => new
{
TestModelId = table.Column<int>(nullable:false)
.Annotation("SqlServer:Identity", "1, 1"),
CreatedOn = table.Column<DateTime>(nullable:false)
},
...
Now I'm trying to get a one-stop place to make sure the CreatedOn
column builder has the default GETDATE()
in there:现在我正在尝试获得一个一站式的地方,以确保CreatedOn
列构建器在其中具有默认的GETDATE()
:
CreatedOn = table.Column<DateTime>(nullable:false, defaultValueSql: "GETDATE()")
which I know works perfectly when translating it to the SQL Server side, but I've tried several data annotation and constructor versions as per the linked question to no avail eg the attribute我知道在将其转换为 SQL 服务器端时效果很好,但是我根据链接的问题尝试了几个数据注释和构造函数版本,但无济于事,例如属性
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
does nothing and I don't want to have to manually add the defaultValueSql
part to the migration file every time I create one / it.什么都不做,我不想每次创建一个 / 它时都必须手动将defaultValueSql
部分添加到迁移文件中。
So where can I do this in the models?那么我在哪里可以在模型中做到这一点?
You can accomplish that in the DbContext class:您可以在 DbContext class 中完成此操作:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Property(x => x.CreatedOn).HasDefaultValueSql("getdate()");
.....
});
edit: needed to have the entity property of the modelBuilder in there too:编辑:也需要有modelBuilder的实体属性:
modelBuilder.Entity<TestModel>().Property...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.