【问题标题】:NHibernate simple one-to-many mapping using NHibernate.Mapping.AttributesNHibernate 使用 NHibernate.Mapping.Attributes 进行简单的一对多映射
【发布时间】:2010-02-19 01:45:00
【问题描述】:

谁能给我提供一个非常清楚地描述基于属性的简单一对多映射的网络链接?

例如(一家公司只能有一个原产国。但一个国家有很多公司):

class Company
{
}

class Country
{
    IList<Company> Items;
}

【问题讨论】:

    标签: nhibernate


    【解决方案1】:

    对于您的示例类,并为无序集合使用包:

    using Map = NHibernate.Mapping.Attributes;
    
    [Map.Class( 0, Table = "country", NameType=typeof(Country) )]
    public class Country
    {
        [Map.Id( 1, Name = "Id" )]
        [Map.Generator( 2, Class = "identity" )]
        public virtual int Id { get; set; }
        [Map.Property]
        public virtual string Name { get; set; }
        [Map.Bag( 0, Table = "country_company" )]
        [Map.Key( 1, Column = "countryid" )]
        [Map.OneToMany( 2, ClassType = typeof( Company ) )]
        public virtual IList<Company> Items { get; set; } 
    }
    
    [Map.Class( 0, Table = "country_company", NameType = typeof( Company ) )]
    public class Company
    {
        [Map.Id( 1, Name = "Id" )]
        [Map.Generator( 2, Class = "identity" )]
        public virtual Guid Id { get; set; }
        [Map.Property]
        public virtual string Name { get; set; }
    }
    

    生成以下 hbm.xml:

    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
        <class name="nh.Country, nh" table="country">
            <id name="Id">
                <generator class="identity" />
            </id>
            <property name="Name" />
            <bag name="Items" table="country_company">
                <key column="countryid" />
                <one-to-many class="nh.Company, nh" />
            </bag>
        </class>
        <class name="nh.Company, nh" table="country_company">
            <id name="Id">
                <generator class="identity" />
            </id>
            <property name="Name" />
        </class>
    </hibernate-mapping>
    

    【讨论】:

      猜你喜欢
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多