对于那些可能对我目前用于使用 OrmLite 实现自定义序列化的包装器模式感兴趣的人(也可以与其他 ORM 一起使用),这是一个简单的工作示例,NodaTime
其中包含未正确序列化的类型:
public class BusinessObject {
public class Poco {
public readonly BusinessObject BusinessObject;
public Poco(BusinessObject businessObject) {
this.BusinessObject = businessObject;
}
public Poco() {
this.BusinessObject = new BusinessObject();
}
public string Id {
get { return this.BusinessObject.Id; }
set { this.BusinessObject.Id = value; }
}
public decimal Amount {
get { return this.BusinessObject.Amount; }
set { this.BusinessObject.Amount = value; }
}
public DateTime Dt {
get { return this.BusinessObject.Dt.ToDateTime(); }
set { this.BusinessObject.Dt = LocalDateTime.FromDateTime(value).Date; }
}
public string TimeZone {
get { return this.BusinessObject.TimeZone.Id; }
set { this.BusinessObject.TimeZone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(value); }
}
public string Description {
get { return this.BusinessObject.Description; }
set { this.BusinessObject.Description = value; }
}
}
public string Id { get; private set; }
public decimal Amount { get; private set; }
public LocalDate Dt { get; private set; }
public DateTimeZone TimeZone { get; private set; }
public string Description { get; private set; }
public BusinessObject() { }
public BusinessObject(string id, decimal amount, LocalDate dt, DateTimeZone timeZone, string description) {
this.Id = id;
this.Amount = amount;
this.Dt = dt;
this.TimeZone = timeZone;
this.Description = description;
}
}
我希望很快可以为应该使用自定义代码处理的特定类型定义挂钩/回调,并且 OrmLite 将允许从持久性中重新加载具有私有设置器的属性(目前它只能在一个方向上工作)。
更新 (2014/03/08):作为一种临时解决方法,可以让 OrmLite 通过首先调用来使用自定义序列化/反序列化:
JsConfig<BusinessObject>.TreatValueAsRefType = true;
即使BusinessObject
是引用类型。然后,您可以享受以下的美丽/简单/无处不在:
JsConfig<BusinessObject>.RawSerializeFn = bo => bo.Serialize();
JsConfig<BusinessObject>.RawDeserializeFn = str => BusinessObject.Deserialize(str);
希望很快会添加对自定义映射的支持(例如,可以将 NodaTime.LocalDate 映射到 DateTime 而不是字符串)。