我猜测 SQL EF 生成的是设置字段值。即使你不在代码中设置,EF也不知道数据库有默认值,也不知道他应该忽略它。
This article,从 2011 年开始,表示有一个 DatabaseGenerated 属性,您可以像这样使用它:
[DatabaseGenerated(DatabaseGenerationOption.Computed)]
public DateTime RegistrationDate { get; set; }
所以,EF 现在知道它应该在查询数据库时检索数据,但应该依赖数据库来设置值。
但是,如果您明确设置该值,我不知道它会做什么。也许它会忽略它,这可能不是你真正想要的。
我没有测试它,这只是一个猜测,但在我看来这是一个不错的解决方案。
[Edit1] 几个月前,我在 49:12 看到了 this video,这家伙在他的 DbContext 课程中做了这样的事情(我相信你有)(视频在葡萄牙语)(我修改了代码,但没有测试):
//This method will be called for every change you do - performance may be a concern
public override int SaveChanges()
{
//Every entity that has a particular property
foreach (var entry in ChangeTracker.Entries().Where(entry => entry.Entity.GetType().GetProperty("YourDateField") != null))
{
if (entry.State == EntityState.Added)
{
var date = entry.Property("YourDateField");
//I guess that if it's 0001-01-01 00:00:00, you want it to be DateTime.Now, right?
//Of course you may want to verify if the value really is a DateTime - but for the sake of brevity, I wont.
if (date.CurrentValue == default(DateTime))
{
date.CurrentValue = DateTime.Now;
}
else //else what?
{
//Well, you don't really want to change this. It's the value you have set. But i'll leave it so you can see that the possibilities are infinite!
}
}
if (entry.State == EntryState.Modified)
{
//If it's modified, maybe you want to do the same thing.
//It's up to you, I would verify if the field has been set (with the default value cheking)
//and if it hasn't been set, I would add this:
date.IsModified = false;
//So EF would ignore it on the update SQL statement.
}
}
}