Many to many example - 1 of 4

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

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

  <class name="Product" table="Product">

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

      <generator class="guid.comb"/>

    </id>

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

    <bag name="Orders" generic="true" table="ProductOrder" cascade="save-update">

      <key column="ProductId" />

      <many-to-many column="OrderId" class ="Order" />

    </bag>

  </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="Order" table="[Order]">

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

      <generator class="guid.comb"/>

    </id>

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

    <bag name="Products" generic="true" table="ProductOrder" cascade="save-update">

      <key column="OrderId" />

      <many-to-many column="ProductId" class ="Product"/>

    </bag>

  </class>

</hibernate-mapping>
namespace TstDBConnection.Entities

{

    public class Order

    {

        public virtual Guid Id { get; set; }

        public virtual string Name { get; set; }

        public virtual IList<Product> Products { get; set; }

    }

}
namespace TstDBConnection.Entities

{

    public class Product

    {

        public virtual Guid Id { get; set; }

        public virtual string Name { get; set; }

        public virtual IList<Order> Orders { get; set; }

    }

}
        public static void TestMany2Many(ISessionFactory sessionFactory)

        {

            using (ISession session = sessionFactory.OpenSession())

            {

                Product product = new Product() { Name = "A product" };

                Order order = new Order()

                {

                    Products = new List<Product>() { product },

                    Name = "Coffee CupBox"

                };

                var id = session.Save(order);

                session.Flush();

            }

        }
        static void Main(string[] args)

        {

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

            Configuration configuration = new Configuration();

            configuration.Configure();

            ISessionFactory sessionFactory = configuration.BuildSessionFactory();



            TestMany2Many(sessionFactory);



            sessionFactory.Close();

        }

你可能感兴趣的:(example)