Best practice for Handling NHibernate parent-child collections

后端 未结 7 982
逝去的感伤
逝去的感伤 2020-12-15 10:35

So in a typical model where you have a parent that can have many children and a child that can have only one parent, how do you manage the adding of children. I have been u

7条回答
  •  温柔的废话
    2020-12-15 10:53

    I support the accepted solution to this question, however the solution presented is not complete, as using private fields requires some extra configuration in the mappers. For the benefit of others, the following is the complete solution:

    public partial class Test
    {
        private readonly IList children = new List();
        public virtual IEnumerable Children
        {
            get
            {
                return children;
            }
        }
    }
    

    Note that the publicly exposed collection must be virtual for NHibernate to use it. I also like to make it a readonly field that is initialised when the class is created to ensure it exists in all scenarios. Here is the associated mapper:

    public class TestMap : ClassMap
    {
        ...
        HasMany(s => s.Children).Access.CamelCaseField();
    }
    

    The Access property tells NHibernate to use the private field when mapping values into the model. There are also other options on the Access property allowing various naming configurations to be used.

提交回复
热议问题