我在流畅的休眠中定义一棵树时遇到了麻烦。我以前做过其他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);
}