NHibernate Cookbook 学习笔记 6

枚举类型映射

1.添加一个枚举类型:

public enum AccountTypes
{
  Consumer,
  Business,
  Corporate,
  NonProfit
}


2.添加一个Account类:

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.添加一个account的配置文件:

<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" />
</class>


4.添加type=“NHibernate.Type.EnumStringType`1[[MappingEnums.AccountTypes, MappingEnums]], NHibernate”到<property name="AcctType" not-null="true" />中,这样,数据库中保存的就不是int类型的枚举值,而是具体的字符串表示的值


创建组合模型:

如果有一个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; }

然后有一个customer类:
public virtual string Name { get; set; }
public virtual Address BillingAddress { get; set; }
public virtual Address ShippingAddress { get; set; }

配置文件如下的话:

<?xml version="1.0" encoding="utf-8" ?>
<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>


将生成如下的数据表:对应的实体模型也在下面:

这样使得,address在每个customer中是自动加载的。不会延迟加载。这样做个人感觉可扩展性不好,因为以后如果还要添加其他的地址数据的那又需要添加表的栏位了。这样搞的整张表很大。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值