0

在 NHibernate 中,我定义了一个类及其映射。我不确定复合键定义和 equals/GetHashCode 是否正确?

[DataMember]
public virtual int EXCEPTION_ID { get; set; }

[DataMember]
public virtual int RUNID { get; set; }

[DataMember]
public virtual int ROW_ID { get; set; }

[DataMember]
public virtual string FIELD_NAME { get; set; }

[DataMember]
public virtual string FIELD_VALUE { get; set; }

public override bool Equals(object obj)
{
   if (obj == null)
   {
      return false;
   }

   var t = obj as ExceptionFld;

   if ((EXCEPTION_ID == t.EXCEPTION_ID) && (RUNID == t.RUNID) && (ROW_ID == t.ROW_ID) && (FIELD_NAME == t.FIELD_NAME))
   {
      return true; 
   }     

   return false;
}        

public override int GetHashCode()
{
    return (EXCEPTION_ID + "|" + RUNID + "|" + ROW_ID + "|" + FIELD_NAME).GetHashCode();
}

映射文件是

 <composite-id>
      <key-property name="EXCEPTION_ID"/>
      <key-property name="RUNID"/>
      <key-property name="ROW_ID"/>
      <key-property name="FIELD_NAME"/>
    </composite-id>

    <property name="EXCEPTION_ID" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" not-null="true">
      <column name="EXCEPTION_ID" />
    </property>

    <property name="RUNID" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" not-null="true">
      <column name="RUNID" />
    </property>

    <property name="ROW_ID" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" not-null="true">
      <column name="ROW_ID" />
    </property>

    <property name="FIELD_NAME" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" not-null="true">
      <column name="FIELD_NAME" />
    </property>

    <property name="FIELD_VALUE" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" not-null="true">
      <column name="FIELD_VALUE" />
    </property>
4

1 回答 1

0

据我所知,您不应该重新composite-id声明标签之外的属性(参见示例)。

我会像这样重写 Equals 实现:

public override bool Equals(object obj)
{
    var t = obj as ExceptionFld;

    if (t == null) return false;

    return EXCEPTION_ID == t.EXCEPTION_ID
         && RUNID == t.RUNID
         && ROW_ID == t.ROW_ID
         && FIELD_NAME == t.FIELD_NAME;
}

因为我相当确定您当前的实现在这样调用时会抛出 NullReferenceException:

var instance = new ExceptionFld();
instance.Equals("");

当它真的应该返回false时。

操作员会as尝试从stringto强制转换ExceptionFld,注意强制转换会失败,然后 t 将为空。

我不确定你GetHashCode的性能或哈希码分布,但除此之外,它看起来是可行的。

于 2012-07-10T19:42:56.340 回答