我试图在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