编辑时,DateCreated无效

时间:2013-05-06 20:46:05

标签: sql-server entity-framework asp.net-mvc-4 ef-code-first

我首先尝试使用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字段为空。发生了什么事?

谢谢, 布赖恩

0 个答案:

没有答案