Reputation: 898
We need to log specific action in MVC 3 project. A database table will store logs something like:
"User [SessionUserHere...] changed [Name][Lastname][OtherAttributesHere...] values of [ChangedEmployeeHere...]"
I need to learn which attributes of a model changed and which ones keep their original values. Is there any way to track which attributes of a Model changed?
In MVC3 doing Audit trail a database trigger is proposed; but we use Sql Server Compact for this project.
Thanks...
Upvotes: 2
Views: 1341
Reputation: 7584
I created a library to do just this and provide some additional metadata. It relies on MVC ModelMetadata
and DataAnnotations
to provide a "readable version" of the diff for non technical users.
https://github.com/paultyng/ObjectDiff
Given objects like (no metadata obviously):
var before = new
{
Property1 = "",
MultilineText = "abc\ndef\nghi",
ChildObject = new { ChildProperty = 7 },
List = new string[] { "a", "b" }
};
var after = new
{
Property1 = (string)null,
MultilineText = "123\n456",
NotPreviouslyExisting = "abc",
ChildObject = new { ChildProperty = 6 },
List = new string[] { "b", "c" }
};
It would output something like:
ChildObject - ChildProperty: '6', was '7'
List - [2, added]: 'c', was not present
List - [removed]: No value present, was 'a'
MultilineText:
-----
123
456
-----
was
-----
abc
def
ghi
-----
NotPreviouslyExisting: 'abc', was not present
Upvotes: 0
Reputation: 15015
You could do the audit in code rather than the database. In the HttpPost handler, get the original value and compare the objects using an auditing function. I have a home brew implementation, but this does a similar thing Compare .NET Objects.
It means you can do the following:
var original = GetDatabaseRecord(xx);
var newRec = GetFormSubmission(); // However you do this
var auditor = new CompareObjects();
if ( auditor.Compare(original, newRec) )
{
foreach ( var diff in auditor.Differences )
{
// work through the deltas
}
}
else
{
// Nothing changed!
}
My own version returns a structure of:
The link provided may suffice for you or act as a starting point.
Upvotes: 1
Reputation: 9695
Have you had look at the INotifyPropertyChanged interface?
http://msdn.microsoft.com/en-us/library/ms743695.aspx
Upvotes: 1