[英]Bare-bones shallow serialization of ado.net entity
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. 我意识到关于ADO.Net实体的序列化已经发布了很多问题,但是我没有运气找到一个真正可以解决我想要做的事情。
Basically, I need a really bare-bones, shallow JSON or plain-object representation of an ADO.Net entity. 基本上,我需要一个ADO.Net实体的准系统,浅层JSON或纯对象表示。 The purpose is for change-logging;
目的是进行变更记录; ie 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
? ...任何实现
MySerializer.serialize
快捷方式?
Thanks! 谢谢!
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. 我有一个接口
IConverter<TInputType, TOutputType>
,您可以从中创建一个转换器以将代码(或您想执行的任何操作)注入代码中。
public interface IEmployeeFromDatabaseToBasicEmployeeModelConverter
: IConverter<TheDBType, MyEmployeeModel>{}
public class EmployeeFromDatabaseToBasicEmployeeModelConverter :
IEmployeeFromDatabaseToBasicEmployeeModelConverter
{
public MyEmployeeModel Invoke(TheDBType myDbTypeObject)
{
return new MyEmployeeModel{
// set properties.
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.