映射组件
有时候我们会重复的用到一些数据,但我们又没有必要在用一个实例表示它们。比如地址,有家庭地址,工作地址,而地址就那个重复用到的数据,我们可以把它独立出来。在NHibernate中表示就是组件(component)
1 先定义一个Address类:
public virtual string Lines { get; set; } public virtual string City { get; set; } public virtual string State { get; set; } public virtual string ZipCode { get; set; }
2 再定义一个customer类:
public virtual string Name { get; set; } public virtual Address BillingAddress { get; set; } public virtual Address ShippingAddress { get; set; }
注意到后面两个属性的数据类型是Address
下面看看如何在对应的配制文件中配制:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="ComponentExamples" namespace="ComponentExamples"> <class name="Customer"> <id name="Id"> <generator class="guid.comb" /> </id> <property name="Name" not-null="true" /> <component name="BillingAddress" class="Address"> <property name="Lines" not-null="true" /> <property name="City" not-null="true" /> <property name="State" not-null="true" /> <property name ="ZipCode" not-null="true" /> </component> <component name="ShippingAddress" class="Address"> <property name="Lines" not-null="true" column="ShippingLines" /> <property name="City" not-null="true" column="ShippingCity" /> <property name="State" not-null="true" column="ShippingState" /> <property name ="ZipCode" not-null="true" column="ShippingZipCode" /> </component> </class> </hibernate-mapping>
注意第二个compoent中有另外指定列名:
最终生成的表如下图所示:
映射枚举类型
1 增加一个枚举类:
public enum AccountTypes { Consumer, Business, Corporate, NonProfit }
2 增加一个要映射的类:
public class Account { public virtual Guid Id { get; set; } public virtual AccountTypes AcctType { get; set; } public virtual string Number { get; set; } public virtual string Name { get; set; } }
3 配置XML文件:
<class name="Account"> <id name="Id"> <generator class="guid.comb" /> </id> <natural-id> <property name="Number" not-null="true" /> </natural-id> <property name="Name" not-null="true" /> <property name="AcctType" not-null="true" type="NHibernate.Type.EnumStringType`1[[MappingEnums.AccountTypes, MappingEnums]], NHibernate" /> </class>
注意最后一个节点增加了type属性,值为:NHibernate.Type.EnumStringType`1[[MappingEnums.AccountTypes,MappingEnums]], NHibernate
其中MappingEnums.AccountTypes为枚举类,MappingEnums为对应的命名空间。