实体框架7软删除

时间:2016-03-25 07:54:12

标签: entity-framework asp.net-core-mvc .net-core

net core

我如何在.net core或mvc6

中的实体框架7中实现软删除

在实体框架6中易于实现,但我不知道DNX中的软件包安装并在实体框架7中实现软删除

请帮我晒黑。

1 个答案:

答案 0 :(得分:1)

您可以覆盖SaveChanges功能。

    public override int SaveChanges()
    {
        var objectStateEntries = ChangeTracker.Entries()
      .Where(e => e.Entity is BaseEntity && e.State != EntityState.Detached && e.State != EntityState.Unchanged).ToList();
        var currentTime = DateTime.UtcNow;
        foreach (var entry in objectStateEntries)
        {
            var entityBase = entry.Entity as BaseEntity;
            if (entityBase == null) continue;
            switch (entry.State)
            {
                case EntityState.Deleted:
                    {
                        entry.State = EntityState.Modified;
                        entityBase.DeletedTime = currentTime;
                        entityBase.IsDeleted = true;
                        break;
                    }
                case EntityState.Modified:
                    entityBase.UpdatedTime = currentTime;
                    break;
                case EntityState.Added:
                    entityBase.CreatedTime = currentTime;
                    break;
                default:
                    break;
            }
        }
        return base.SaveChanges();
    }

我的BaseEntity类:

public class BaseEntity
{
    public Guid Id { get; set; }
    public DateTime CreatedTime { get; set; }
    public DateTime? UpdatedTime { get; set; }
    public DateTime? DeletedTime { get; set; }

    public bool IsDeleted { get; set; }
}