在SaveChanges()中返回字典

时间:2015-05-04 18:35:20

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

我正在覆盖ChangeTracker方法,以便我可以使用Dictionary<string, string>来获取实体的已修改属性。我需要返回Audit Service个已修改的属性,以便在我的控制器中调用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(); } 。到目前为止,我的SaveChanges()方法看起来像:

modifiedProperties

有没有办法访问我的控制器中的if (validator.IsValid()) { _workRequestRepo.Save(workRequest); _auditService.Log(UserId, modelId, "Work Order", "Edit", modifiedProperties); } 字典,以便将其传递给我的服务?

控制器:

css/img/file.jpg

2 个答案:

答案 0 :(得分:3)

您不必返回修改后的属性,您可以在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();
    }

答案 1 :(得分:1)

使用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;
  }
}