EntityFramework-Plus icon indicating copy to clipboard operation
EntityFramework-Plus copied to clipboard

EF-Core old and new value are identical

Open Alexxtheonly opened this issue 9 years ago • 3 comments

Our saved AuditEntryProperties have the same value for both old and new value.

The controller method we use to update:

    [HttpPost]
    public IActionResult UpdateRole([FromBody]Role role)
    {
      Context.Roles.AsNoTracking().Get(role.Id);
      Context.Update(role);
      Context.SaveChanges(User);

      return Ok(role);
    }

The SaveChanges() method of our context.

    public int SaveChanges(long? userId)
    {
      var audit = new Audit().SetCreator(userId);

      audit.PreSaveChanges(this);
      var affectedRows = base.SaveChanges();
      audit.PostSaveChanges();

      if (audit.Configuration.AutoSavePreAction != null)
      {
        audit.Configuration.AutoSavePreAction(this, audit);
        base.SaveChanges();
      }

      return affectedRows;
    }

Values are wrong added after calling audit.PreSaveChanges(this);

Thanks in advance.

Alexxtheonly avatar Mar 13 '17 17:03 Alexxtheonly

Hello @Alexxtheonly ,

Could you read the following Issue: https://github.com/zzzprojects/EntityFramework-Plus/issues/8#issuecomment-222166610

I believe it could be very similar.

Let me know if you need more information

Best Regards,

Jonathan

JonathanMagnan avatar Mar 13 '17 18:03 JonathanMagnan

Thank you for your response @JonathanMagnan ,

unfortunately the AddOrUpdate method is not yet implemented in ef core. http://stackoverflow.com/questions/36208580/what-happened-to-addorupdate-in-ef-7

I will write a method myself and report back later.

Alexxtheonly avatar Mar 14 '17 06:03 Alexxtheonly

Reporting back.

Wrote this method:

    /// <summary>
    /// Sets all property values of the <paramref name="other"/> that are not equal
    /// </summary>
    /// <typeparam name="T">The type</typeparam>
    /// <param name="one">The object whose values will be set</param>
    /// <param name="other">The object whose values will be used</param>
    public static void SetValuesOf<T>(this T one, T other)
    {
      var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanWrite && p.CanRead);

      foreach (var property in properties)
      {
        var value = property.GetValue(other);

        if (!Equals(property.GetValue(one), value))
        {
          property.SetValue(one, value);
        }
      }
    }

called like this:

    [HttpPost]
    public IActionResult UpdateRole([FromBody]Role role)
    {
      Context.Roles.Get(role.Id).SetValuesOf(role);
      Context.SaveChanges(User);

      return Ok(role);
    }

Now old and new value are correct.

Alexxtheonly avatar Mar 14 '17 07:03 Alexxtheonly