我有两个简单的类,父和子。 Parent有一组Child对象。
[Serializable, DataContract(IsReference = true)]
public class Child
{
[DataMember]
public virtual int Id { get; set; }
[DataMember]
public virtual DateTime Version { get; set; }
}
[Serializable, DataContract(IsReference = true)]
public class Parent
{
private IList<Child> _children = new List<Child>();
[DataMember]
public virtual int Id { get; set; }
[DataMember]
public virtual DateTime Version { get; set; }
[DataMember]
public virtual IList<Child> Children
{
get { return _children; }
set { _children = value; }
}
}
它们的映射如下:
public class ChildMap : ClassMap<Child>
{
public ChildMap()
{
Schema(CommonMapSettings.SchemaName);
Table("Child");
Id(x => x.Id);
Version(x => x.Version);
}
}
public class ParentMap : ClassMap<Parent>
{
public ParentMap()
{
Schema(CommonMapSettings.SchemaName);
Table("Parent");
Id(x => x.Id);
Version(x => x.Version);
HasMany(x => x.Children).KeyColumn("ParentId").Cascade.AllDeleteOrphan();
}
}
我有一个测试:
复制的合并是否与原始版本相同。
// Create a parent with a child.
var parent = new Parent();
parent.Children.Add(new Child());
// Save the object graph.
using (var session = SessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
session.SaveOrUpdate(parent);
transaction.Commit();
}
}
// Create a copy of the entire object graph by serializing it to a memory stream and back
var serializer = new DataContractSerializer(parent.GetType());
var memoryStream = new MemoryStream();
serializer.WriteObject(memoryStream, parent);
memoryStream.Position = 0;
Parent serializedParent = (Parent)serializer.ReadObject(memoryStream);
// Merge, use the copy which is identical. No changed should be saved.
using (var session = SessionFactory.OpenSession()
{
using (var transaction = session.BeginTransaction())
{
serializedParent = session.Merge(serializedParent);
transaction.Commit();
}
}
// Fails. NHibernate updated Version on Parent.
Assert.AreEqual(parent.Version, serializedParent.Version);
未对父级或子级进行任何更改,并且合并是在新会话中完成的,那么为什么父级会获得新版本?