Currently, I’m working on an Angular (front-end) C# (back-end) application. This application uses Entity Framework code first.
I’m going to work with an Activity Log, basically to save changes inside an app Profile section, so I think about the following model for that:
public partial class ProfileActivity : BaseAuditModel, IEntity
{
public string Description { get; set; }
public int ProfileId { get; set; }
public virtual Profile Profile { get; set; }
public int ActivityTypeId { get; set; }
public string OldValue { get; set; }
public string NewValue { get; set; }
}
Well, now on update endpoint (controller), I receive data from the front end as:
[Authorize]
[HttpPost("AddProfile")]
[CleanCache]
public async Task<ActionResult<Profile>> AddProfile(Profile profile)
{
var user = await this.GetUser();
var model = await _profileService.EditProfile(profile, user);
if (model != null) return Ok(model);
return NotFound();
}
My question is right here. How can I compare the received model (with changes) with the current Profile (with no changes yet)? I can get the model without changes by doing a get operation before saving the changes as:
var currentProfile = GetProfile(profile.Id);
But now, how can I identify all the changes between received profile model and the currentProfile?
Profile Model:
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public DateTime? DateOfBirth { get; set; }
public int VettingStatusId { get; set; }
public int? RecruiterId { get; set; }
etc..
So, at the end of the date, I can insert into my new table ProfileActivity
all the changes where we found the differences.
2
Answers
You can use reflection, for example:
From your description, I think you wanna compare two objects and put the different properties into a list mdoel. So you can refer to this simple demo:
NuGet Package:
Model:
Demo:
You can see the propertiy name, old value and new value have been inserted into the list model.
=======Update======