NH表关系多对多分析

    技术2022-06-27  45

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

        }

    b.    映射

     

    <class name="Parent">

        <id name="Id">

          <generator class="guid" />

        </id>

        <!--完全由parent来控制,因为引入了第三个表ChildSet,所以设置cascade-->

        <!--<set name="Children" table="ChildSet" inverse="false" lazy="true" cascade="all">-->

     

        <!--child来控制,只保存了parent-->

        <!--<set name="Children" table="ChildSet" inverse="true" lazy="true" >-->

     

       

        <!--将保存parent,child,不保存childSet-->

        <set name="Children" table="ChildSet" inverse="true" lazy="true" cascade="all" >

          <key column="parent_id"/>

          <many-to-many class="Child" column="child_id" />

        </set>

      </class>

     

    <class name="Child">

        <id name="Id">

          <generator class="guid" />

        </id>

        <property name="Name"/>

      </class>

     

    c.    测试代码:

    [Test]

            public void CreateInitialDataManytoMany()

            {

                using (ISession session = _sessionFactory.OpenSession())

                using (ITransaction transaction = session.BeginTransaction())

                {

                    Parent p1 = new Parent();

                    Parent p2 = new Parent();

                    Child c1 = new Child();

                    c1.Name = "c1";

     

                    Child c2 = new Child();

                    c2.Name = "c2";

                    //one parent two child

                    p1.Children.Add(c1);

                    p1.Children.Add(c2);

                    //two parent one child

                    p2.Children.Add(c1);

                    session.Save(p1);

                    session.Save(p2);

                    transaction.Commit();

                }

            }

    d.    总结:

    Many-to-manny 引入了第三个表childSet,注意cascadeinverse设置不同所产生的效果


    最新回复(0)