2

我在流畅的休眠中定义一棵树时遇到了麻烦。我以前做过其他HasMany关系,但没有像这样自我引用。

无论我尝试什么,Children == null.

实体:

public class StockContainer
{
    public virtual Guid Id { get; set; }

    public virtual string Name { get; set; }

    public virtual StockContainer Parent { get; set; }
    public virtual IList<StockContainer> Children { get; set; }

    public virtual void MoveTo(StockContainer outerContainer)
    {
        Parent = outerContainer;
    }
}

流畅的 NHibernate 映射:

public class StockContainerMapping : ClassMap<StockContainer>
{
    public StockContainerMapping()
    {
        Table("StockContainers");
        Id(x => x.Id);
        Map(x => x.Name).Unique();
        References(n => n.Parent).LazyLoad().Nullable();
        HasMany(n => n.Children).KeyColumn("Parent_id").Where(x => x.Parent.Id == x.Id);
    }
}

生成的表:

create table StockContainers (
    Id UNIQUEIDENTIFIER not null,
   Name TEXT unique,
   Parent_id UNIQUEIDENTIFIER,
   primary key (Id),
   constraint FKB5FA0632A80E0632 foreign key (Parent_id) references StockContainers
)

失败的单元测试:

    [TestMethod]
    public void Can_move_an_item()
    {
        var item1 = LoadByName("Item1"); //test helper function that loads items from repository
        var item2 = LoadByName("Item2");

        //pair them up
        using (var transaction = _session.BeginTransaction())
        {
            item2.MoveTo(item1);
            transaction.Commit();
        }

        //reload them
        item1 = LoadByName("Item1");
        item2 = LoadByName("Item2");

        Assert.AreEqual(item1, item2.Parent); //OK
        Assert.IsNotNull(item1.Children);     //Fails here
        Assert.AreEqual(1, item1.Children.Count);
    }
4

1 回答 1

0

啊,我必须在再次加载它们之前使用另一个会话,否则我会得到相同的实体。

    _session = CreateSession(); //(Test class method to create session)

    //reload them
    var item1b = LoadByName("Item1");
    var item2b = LoadByName("Item2");

    //check we have loaded new objects
    Assert.AreNotSame(item1, item1b);
    Assert.AreNotSame(item2, item2b);
于 2013-08-13T08:51:20.140 回答