Return SaveChanges() 中的字典

Return Dictionary in SaveChanges()

我正在覆盖 SaveChanges() 方法,以便我可以使用 ChangeTracker 来获取实体的修改属性。我需要 return 修改属性的 Dictionary<string, string>,以便在我的控制器中我可以调用 Audit Service。到目前为止,我的 SaveChanges() 方法看起来像:

public override int SaveChanges()
{
    var changeInfo = ChangeTracker.Entries()
        .Where(t => t.State == EntityState.Modified)
        .Select(t => new {
            Original = t.OriginalValues.PropertyNames.ToDictionary(pn => pn, pn => t.OriginalValues[pn]),
            Current = t.CurrentValues.PropertyNames.ToDictionary(pn => pn, pn => t.CurrentValues[pn])
        });

    Dictionary<string, string> modifiedProperties = new Dictionary<string, string>();
    foreach (var item in changeInfo)
    {
        foreach (var origValue in item.Original)
        {
            var currValue = item.Current[origValue.Key];
            if ((origValue.Value != null && currValue != null) && !origValue.Value.Equals(currValue))
            {
                modifiedProperties.Add(origValue.Key, string.Format("Old Value: {0}, New Value: {1}", origValue.Value, currValue));
            }
        }
    }
    return base.SaveChanges();
}

有没有办法在我的控制器中访问 modifiedProperties 字典,以便我可以将其传递给我的服务?

控制器:

if (validator.IsValid())
{
    _workRequestRepo.Save(workRequest);
    _auditService.Log(UserId, modelId, "Work Order", "Edit", modifiedProperties);
}

您不必 return 修改属性,您可以在 SaveChanges 方法中处理您的审核程序。这是一个例子:

    public MyContainer(IUserProvider userProvider) {
        _userProvider = userProvider;
    }

    public override int SaveChanges() {
        var entities = ChangeTracker.Entries().Where(x => x.Entity is BaseEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));
        if (entities.Any()) {
            User currentUser = _userProvider.GetCurrent();
            if (currentUser == null)
                throw new Exception("Current user is undefined.");
            DateTime time = DateTime.Now;
            foreach (var entity in entities) {
                BaseEntity baseEntity = (BaseEntity)entity.Entity;
                if (entity.State == EntityState.Added) {
                    baseEntity.Created = time;
                    baseEntity.CreatedBy = currentUser;
                }
                baseEntity.Modified = time;
                baseEntity.ModifiedBy = currentUser;

                // get and store the changed properties of the entity here
                // ....
                var changeInfo = entities.Select(t => new { Original = t.OriginalValues.PropertyNames.ToDictionary(pn => pn, pn => originalValues[pn]), Current = t.CurrentValues.PropertyNames.ToDictionary(pn => pn, pn => t.CurrentValues[pn]);

            }
        }

        return base.SaveChanges();
    }

使用 IOC 我想你有类似的东西:

(这是假设审计而不是修订)

演示文稿:

public PersonController
{
  private IPersonBL _personBL;

  public PersonController(IPersonBL personBL)
  {
    _personBL = personBL
  }

  public ActionResult SavePerson(PersonVM model)
  {
     // if ModelState etc etc
     var person = Mapper.Map<Person>(model);
     _personBL.Save(person)
  }
}

业务层

public PersonBL : IPersonBL
{
  private IAuditService _auditService;
  private IPersonRepo _personRepo;

  public PersonBL(IAuditService auditService,
    IPersonRepo personRepo)
  {
    _auditService = auditService;
    _personRepo = personRepo;
  }

  public void Save(Person person)
  {
    PersonDTO personDTO = Mapper.Map<PersonDTO>(person);
    var result = _personRepo.Save(personDTO);
    if (result.Count > 0)
    {
      _auditService.Audit(result);
    }
  }
}

数据层

public PersonDL : IPersonDL
{
  private DbContext _context;

  public PersonDL(DbContext dbContext)
  {
    _context = dbContext;
  }

  public IDictionary<string, string> Save(PersonDTO person)
  {
    var result = new Dictionary<string, string>()

    _context.Persons.Add(person);
    var saveCount = _context.SaveChanges();

    if (saveCount > 0)
    {
      // Do Object Tracking
      // Populate result;
    }

    return result;
  }
}