我試圖在OnPostUpdate事件中獲取更新實體的舊狀態。 @event參數的OldState屬性將對象作爲數組返回,我需要它作爲對象。我試過如下:NHibernate事件偵聽深克隆對象
public class EventListener : IPostUpdateEventListener {
public void OnPostUpdate(PostUpdateEvent @event) {
// Get the property names to align with the indexes of the old state
var propertyNames = @event.Persister.PropertyNames;
// Get the original entity values
var type = @event.Entity.GetType();
var original = Activator.CreateInstance(type);
// Set the values
for (var i = 0; i < @event.OldState.Length; i++) {
// Get the property and value
var property = type.GetProperty(@event.Persister.PropertyNames[i]);
var value = @event.OldState[i];
if (property.CanWrite && !(@event.Persister.PropertyTypes[i] is CollectionType)) {
if (value != null && (@event.Persister.PropertyTypes[i] is ComponentType || @event.Persister.PropertyTypes[i] is EntityType))
property.SetValue(original, CloneObject(value));
else
property.SetValue(original, value);
}
}
}
這裏的CLONEOBJECT方法:
private object CloneObject(object source) {
var sourceType = source.GetType();
var target = Activator.CreateInstance(sourceType, true);
foreach (var property in type.GetProperties()) {
var value = property.GetValue(source, null);
if (property.CanWrite && (property.PropertyType == typeof(string) || !typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) && !property.PropertyType.IsInterface) {
if (value != null && typeof(IEntity).IsAssignableFrom(property.PropertyType))
property.SetValue(target, CloneObject(value));
else
property.SetValue(target, value);
}
}
return target;
}
我做的第一件事是環比在原來的對象的屬性,然後我試圖處理組件和引用類型(忽略列表)。這會正確複製對象。然而,隨後引發錯誤:
collection [Models.ContentType.Tags] was not processed by flush()
編輯:將contentType類是我更新的屬性的一個類型。這是它的實施,因爲它幫助:
public class ContentType : Entity<int> {
public virtual string Name { get; set; }
public virtual IList<ContentTag> Tags { get; set; }
public ContentType() {
Tags = new List<ContentTag>();
}
}
我也遇到類似的錯誤,當我試圖讓其他實體的舊狀態。如果有人能告訴我正確的方式來做到這一點,我會很感激。由於
您遇到了什麼問題? –
每當它更新實體時,我都會收到錯誤「集合[Models.User.Addresses]未由flush()處理」。 – nfplee