One to many example - 2 of 4

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="TstDBConnection.Entities" assembly="TstDBConnection">

  <class name="Cup" table="Cup">

    <id name="Id" column="Id">

      <generator class="guid.comb"/>

    </id>

    <property name="Name" column="Name"></property>

  </class>

</hibernate-mapping>
<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="TstDBConnection.Entities" assembly="TstDBConnection">

  <class name="CupBox" table="CupBox">

    <id name="Id" column="Id">

      <generator class="guid.comb"/>

    </id>

    <property name="Name" column="Name"></property>

    <set name="Cups" lazy="true" fetch="join" cascade="all-delete-orphan">

      <key column="CupBoxId"/> <!--Cup table column-->

      <one-to-many class="Cup"/> <!--it stands for get related info from cup.hbm.xml-->

    </set>

  </class>

</hibernate-mapping>
namespace TstDBConnection.Entities

{

    public class CupBox

    {

        public virtual Guid Id { get; set; }

        public virtual string Name { get; set; }

        public virtual Iesi.Collections.Generic.ISet<Cup> Cups { get; set; }

    }

}
namespace TstDBConnection.Entities

{

    public class Cup

    {

        public virtual Guid Id { get; set; }

        public virtual string Name { get; set; }

    }

}
        public static void TestOne2Many(ISessionFactory sessionFactory)

        {

            using (ISession session = sessionFactory.OpenSession())

            {

                Cup cup = new Cup() { Name = "Coffee Cup" };

                CupBox cupbox = new CupBox()

                {

                    Cups = new Iesi.Collections.Generic.HashedSet<Cup>() { cup },

                    Name = "Coffee CupBox"

                };

                var id = session.Save(cupbox);

                session.Flush();

                

                var query = from leafT in session.Query<CupBox>() select leafT;

                IList<CupBox> employees = query.ToList();

                CupBox cb = employees[0];

                List<Cup> cups = cb.Cups.ToList<Cup>();

            }

        }
        static void Main(string[] args)

        {

            log4net.Config.XmlConfigurator.Configure(); // log4net

            Configuration configuration = new Configuration();

            configuration.Configure();

            ISessionFactory sessionFactory = configuration.BuildSessionFactory();



            TestOne2Many(sessionFactory);



            sessionFactory.Close();

        }

你可能感兴趣的:(example)