NH表关系一对多分析

    技术2022-07-01  78

    nhibernate 表之间的几种关系不易把握,现根据个人学习,总结如下,共同学习,提高,

    完整代码参见我的资源[NHibernateTestExampleforSqlServer20110109]

    若有错误,请指出,

    不甚感谢!

     

    a.实体:

    public class Parent

        {

            public Parent()

            {

                children = new HashedSet();

            }

            private Guid id;

            private ISet children;

     

            public virtual Guid Id

            {

                get { return id; }

                set { id = value; }

            }

     

            public virtual ISet Children

            {

                get { return children; }

                set { children = value; }

            }

    }

     

      public class Child

         {

             public Child()

             {

             }

             public virtual Guid  Id { get; set; }

             public virtual string Name { get; set; }

             public virtual Parent Parent { get; set; }

         }

    b.映射:

      <class name="Parent">

        <id name="Id">

          <generator class="guid" />

        </id>   

       

        <!--child控制,不生生更新语句,和一对一差不多-->

        <set name ="Children" inverse="true" lazy="true">

         

        <!--parent控制,将产生更新语句-->

        <!--<set name="Children" lazy="true">-->

          <key column="parent_id"/>

          <one-to-many class="Child"/>

        </set>

      </class>

     

    <class name="Child">

        <id name="Id">

          <generator class="guid" />

        </id>

        <property name="Name"/>

        <many-to-one name="Parent" class="Parent" column="parent_id"></many-to-one>

      </class>

    c.测试代码:

      /// <summary>

            /// 一对多,inverse设置是否产生第三语句的问题

            /// </summary>

            [Test]

            public void CreateInitialDataOnetoMany()

            {

                #region 仅保存parent,主动权在child

                using (ISession session = _sessionFactory.OpenSession())

                using (ITransaction transaction = session.BeginTransaction())

                {

                    Parent p = new Parent();

                    Child c = new Child();

                    p.Children.Add(c);

                    c.Parent = p;

                    session.Save(p);

                    session.Save(c);

                    transaction.Commit();

                }

                #endregion

            }

    d.总结:


    最新回复(0)