我首先尝试使用 ef 代码并遇到问题。
我有一个接口 IAuditable:
public interface IAuditable
{
DateTime? DateCreated { get; set; }
DateTime? DateModified { get; set; }
}
我有我的模型:
public class Tip : IAuditable
{
public int TipId { get; set; }
[Required]
[StringLength(160)]
public string Title { get; set; }
[Required]
[AllowHtml]
public string Content { get; set; }
[Required]
public bool Posted { get; set; }
public DateTime? DateCreated { get; set; }
public DateTime? DateModified { get; set; }
}
然后在我的 DbContext 中,我重写了 SaveChanges 以将正确的值保存到这些字段中:
public override int SaveChanges()
{
DateTime auditDate = DateTime.UtcNow;
foreach (DbEntityEntry<IAuditable> entry in ChangeTracker.Entries<IAuditable>())
{
if (entry.State == EntityState.Added)
{
entry.Entity.DateCreated = auditDate;
entry.Entity.DateModified = auditDate;
}
else if (entry.State == EntityState.Modified)
{
entry.Entity.DateModified = auditDate;
}
}
return base.SaveChanges();
}
项目的创建按预期工作。DateCreated 和 DateModified 已设置。但是,在编辑时,它会设置 DateModified 但会使我的 DateCreated 字段无效。这是怎么回事?
谢谢,布赖恩