NHibernate复合键

时间:2010-04-23 08:02:15

标签: nhibernate composite-key

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

我现在这样做的方法如下:

    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配置文件中。

我当前的配置文件是以下内容:

<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>

3 个答案:

答案 0 :(得分:2)

您可以直接在班级中创建属性...并将其映射为:

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

如果您这样做,则必须覆盖班级中的EqualsGetHashCode

答案 1 :(得分: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;
        }
    }

这样您就不会复制数据,只返回/设置复合键内的数据。

答案 2 :(得分: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可读)