Reputation: 7197
I realize there are loads of questions already posted regarding serialization of ADO.Net entities, but I haven't had any luck finding one that really addresses quite what I want to do.
Basically, I need a really bare-bones, shallow JSON or plain-object representation of an ADO.Net entity. The purpose is for change-logging; i.e. when a record is going to be changed, I want to snag a copy of its data "before" and "after", and log the change.
I don't want any of the navigation, complex or other properties to be considered; just the scalar properties of the entity. If I miss some data that only would appear in special cases, that's fine -- just trying to do a rough log. Ideally my final code should look something like this:
Employee emp = db.Employees.First();
string oldRecordJSON = MySerializer.serialize(emp);
emp.Name = "Fred";
db.saveChanges();
string newRecordJSON = MySerializer.serialize(emp);
ChangeLog.logDBChange("Employees", emp.ID, oldRecordJSON, newRecordJSON, DateTime.Now);
...Any quick & easy way to implement MySerializer.serialize
?
Thanks!
Upvotes: 0
Views: 412
Reputation: 54001
If you're just wanting some specific properties of your employee, consider creating a basic model and serialising that.
var serializer = new JavaScriptSerializer();
serializer.Serialize(new MyEmployeeModel{ // set fields here});
You can build this as a converter if you wish, that's how I'd do it.
I have an interface, IConverter<TInputType, TOutputType>
from which you can create a converter to inject (or whatever you want to do) into your code.
public interface IEmployeeFromDatabaseToBasicEmployeeModelConverter
: IConverter<TheDBType, MyEmployeeModel>{}
public class EmployeeFromDatabaseToBasicEmployeeModelConverter :
IEmployeeFromDatabaseToBasicEmployeeModelConverter
{
public MyEmployeeModel Invoke(TheDBType myDbTypeObject)
{
return new MyEmployeeModel{
// set properties.
}
}
}
Upvotes: 1