HasMany给出了null子项

时间:2013-08-13 08:41:45

标签: c# nhibernate fluent-nhibernate

我在使用流利的nhibernate定义一棵树时遇到了麻烦。我以前做过其他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;
    }
}

Fluent 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);
    }

1 个答案:

答案 0 :(得分: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);