c# - HasMany 给出 null child

标签 c# nhibernate fluent-nhibernate

我在 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;
    }
}

流畅的 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 ,否则我会得到相同的实体。

    _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);

关于c# - HasMany 给出 null child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18204433/

相关文章:

nhibernate - 模糊的 NHibernate/Fluent NHibernate 错误

c# - 如何在 Fluent NHibernate 中映射 IDictionary<string, Entity>

c# - 流利的 nHibernate : Use the same mapping files for tables with the same structure in different schemas

c# - 如何使用 nhibernate 选择字典值中的列?

c# - Fluent NHibernate 删除多个对象

c# - Nhibernate 更新外键实体的版本列

c# - CreditCardAttribute 使用哪种算法进行信用卡号格式验证

c# - 关于枚举的更优雅的设计

c# - '无法使用合并将类型 'void' 隐式转换为 'System.Data.DataTable'

c# - 帮我 XOR 加密