HasMany gives null children
本文关键字:children null gives HasMany | 更新日期: 2023-09-27 18:27:31
我在fluent 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);
}
啊,在再次加载它们之前,我必须使用另一个会话,否则我会得到相同的实体。
_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);