Fluent nHibernate - Mapping Children with Composite Keys Yielding Null References

岁酱吖の 提交于 2019-12-06 02:53:20

As @KeithS points out the problem is that you have mapped the Child collection as HasManyToMany when it should be HasMany. Here is how the mapping should look:

  ChildMap() {
      CompositeId() //This is is good
        .KeyReference(x => x.Parent, "ParentId")
        .KeyReference(x => x.Other, "OtherId");
  }

  ParentMap(){ //This is the fix
        HasMany(c => c.Children)
          .Inverse()
          .Cascade.All()
          .KeyColumn("ParentId") //Not needed if Parent Id prop maps to ParentId col
          .Table("[Test]");
  }

You are not mapping the Parent as a property of the Child. NHibernate (and FluentNH) only map what you tell them to; you could have a dozen fields on your object, but if you only map one of them, that's all NH will provide when it hydrates an instance for you. You should include a "References" method to the Parent in your mapping, specifying the Parent's key field as the FK reference. That should give you the "backreference" you have in your object hierarchy.

Also, it looks like instead of a many-to-many on the Parent side, you should have just a one-to-many (using HasMany). Parents can have many Children, but a Child has one and only one Parent. ManyToMany may work, but it creates a redundant cross-reference table in between Parent and Child.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!