2010-04-23 65 views
1

我已经创建了一个组合键,它正在工作,但理想情况下,我希望行类中单独的直接字段。NHibernate复合键

我这样做目前的方法如下:

private UserPrimaryKey _compositeKey; 
    public virtual UserPrimaryKey CompositeKey 
    { 
     get 
     { 
      if (_compositeKey == null) _compositeKey = new UserPrimaryKey(); 
      return _compositeKey; 
     } 
     set { 
      if (_compositeKey == value) return; 
      _compositeKey = value; 
      Host = value.Host; 
      UserAccount = value.User; 
     } 
    } 
    public string Host { get; set; } 
    public string UserAccount { get; set; } 

,我想知道是否有这样做的没有更好的办法?可能在NHibernate配置文件中。

我现在的配置文件是follwoing:

<class name="TGS.MySQL.DataBaseObjects.DataBasePrivilege,TGS.MySQL.DataBaseObjects" table="user"> 
<composite-id name="CompositeKey" class="TGS.MySQL.DataBaseObjects.UserPrimaryKey, TGS.MySQL.DataBaseObjects"> 
    <key-property name="Host" column="Host" type="string" length="60" /> 
    <key-property name="User" column="User" type="string" length="16" /> 
</composite-id> 
</class> 

回答

2

您可以在类中直接创建的属性...,并与它们映射:

<composite-id> 
    <key-property name="Host"/> 
    <key-property name="UserAccount"/> 
</composite-id> 

如果你这样做,你就必须重写EqualsGetHashCode在你的班级。

+0

实际工作:O – 2010-04-24 20:49:18

+1

当然它!我不会骗你:-D – 2010-04-25 00:11:15

+0

谢谢! :D它工作 – 2010-04-26 08:10:43

1

我建议如下:

private UserPrimaryKey _compositeKey; 
    public virtual UserPrimaryKey CompositeKey 
    { 
     get 
     { 
      if (_compositeKey == null) _compositeKey = new UserPrimaryKey(); 
      return _compositeKey; 
     } 
     set { 
      if (_compositeKey == value) return; 
      _compositeKey = value; 
      Host = value.Host; 
      UserAccount = value.User; 
     } 
    } 
    public string Host 
    { 
     get 
     { 
      return CompositeKey.Host; 
     } 
     set 
     { 
      CompositeKey.Host = value; 
     } 
    } 
    public string UserAccount 
    { 
     get 
     { 
      return CompositeKey.User; 
     } 
     set 
     { 
      CompositeKey.User = value; 
     } 
    } 

这样,你不重复的数据,只返回/套组合键中的数据。

1

我会尽可能避免复合键。与常规唯一约束两列替换:

<class name="DataBasePrivilege" table="user"> 
    <id name="id"> 
    <generator class="hilo"> 
     <param name="table">user_HiLo</param> 
     <param name="max_lo">100</param> 
    </generator> 
    </id> 
    <property name="Host" length="60" unique-key="user_host"/> 
    <property name="User" length="16" unique-key="user_host"/> 
</class> 

(顺便说一句:你不需要指定在通常情况下类型和你不需要,如果他们匹配属性指定的列名。名字这样可以使你xml的读取)

+0

不幸的是,该表是MySQL本地表(用于保存MySQL数据库用户的记录),所以我无法更改该模式。这仍然可以在不改变模式的情况下运行 – 2010-04-23 16:00:44