实体框架UpdateModel没有设置修改标志?

时间:2016-07-12 14:38:09

标签: c# asp.net-mvc entity-framework updatemodel

我在ApplicationDBContext中有以下内容,因此无论何时添加或修改新实体,它都会添加创建或修改的时间戳。它适用于我创建一个实体但在我做更新时似乎失败 - 修改后的日期戳似乎没有更新?

    public override int SaveChanges()
    {
        var modifiedEntries = ChangeTracker.Entries()
            .Where(x => x.Entity is AuditableEntity
                && (x.State == EntityState.Added || x.State == EntityState.Modified));

        foreach (var entry in modifiedEntries)
        {
            AuditableEntity entity = entry.Entity as AuditableEntity;
            if (entity != null)
            {
                string userId = System.Threading.Thread.CurrentPrincipal.Identity.GetUserId();
                DateTime now = DateTime.UtcNow;

                if (entry.State == EntityState.Added)
                {
                    entity.CreatedBy = userId;
                    entity.CreatedDate = now;
                }
                else
                {
                    base.Entry(entity).Property(x => x.CreatedBy).IsModified = false;
                    base.Entry(entity).Property(x => x.CreatedDate).IsModified = false;
                }

                entity.ModifiedBy = userId;
                entity.ModifiedDate = now;
            }
        }

        return base.SaveChanges();
    }

这是我更新模型的控制器操作:

  var post = _postRepository.GetPost(viewModel.Id);

 UpdateModel(post, "", includeProperties: new[] { "Subject", "TypeId", "CategoryId" });

 _unitOfWork.Complete();

_unitOfWork.Complete()只需调用以下内容:

public void Complete()
{
   _context.SaveChanges();
}

Auditable类是Post继承自的一个抽象类:

 public abstract class AuditableEntity 
{
    [ScaffoldColumn(false)]
    public DateTime CreatedDate { get; set; }

    [MaxLength(128)]
    [ScaffoldColumn(false)]
    public string CreatedBy { get; set; }

    [ScaffoldColumn(false)]
    public DateTime ModifiedDate { get; set; }

    [MaxLength(128)]
    [ScaffoldColumn(false)]
    public string ModifiedBy { get; set; }

    public ApplicationUser Creator { get; set; }
    public ApplicationUser Modifier { get; set; }
}

public class Post : AuditableEntity
{
   ...

}

除了modifiedby和modifieddate之外,所有字段都会更新吗?

我的理解是,当您调用UpdateModel时,Entity Framework的自动更改跟踪会在实体上设置Modified标志?

0 个答案:

没有答案