Many to one example - 3 of 4

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

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

  <class name="Tree" table="Tree">

    <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="Leaf" table="Leaf">

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

      <generator class="guid.comb"/>

    </id>

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

    <many-to-one name="Tree" class="Tree" column="TreeId" cascade="save-update" />

  </class>

</hibernate-mapping>
namespace TstDBConnection.Entities

{

    public class Tree

    {

        public virtual Guid Id { get; set; }

        public virtual string Name { get; set; }

    }

}
namespace TstDBConnection.Entities

{

    public class Leaf

    {

        public virtual Guid Id { get; set; }

        public virtual string Name { get; set; }

        public virtual Tree Tree { get; set; }

    }

}
        public static void TestMany2One(ISessionFactory sessionFactory)

        {

            using (ISession session = sessionFactory.OpenSession())

            {

                Tree tree = new Tree() { Name = "Big Tree" };

                Leaf leaf = new Leaf() { Tree = tree, Name = "Leaf A for Big Tree" };

                session.Save(leaf);

                session.Flush();



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

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

            }

        }
        static void Main(string[] args)

        {

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

            Configuration configuration = new Configuration();

            configuration.Configure();

            ISessionFactory sessionFactory = configuration.BuildSessionFactory();



            TestMany2One(sessionFactory);



            sessionFactory.Close();

        }

你可能感兴趣的:(example)