流畅的NHibernate - 分离的集合总是很脏

时间:2014-06-19 14:12:45

标签: c# .net nhibernate fluent-nhibernate

我有两个简单的类,父和子。 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();
    }
}

我有一个测试:

  1. 创建父母和子女。
  2. 将对象图保存到数据库中。
  3. 通过序列化内存流来创建父和子的副本,以模拟向客户端来回发送它。
  4. 复制的合并是否与原始版本相同。

        // 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); 
    
  5. 未对父级或子级进行任何更改,并且合并是在新会话中完成的,那么为什么父级会获得新版本?

0 个答案:

没有答案