在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>
答案 0 :(得分:0)
根据我收集的内容,您应该不重新声明composite-id
标记之外的属性(请参阅example)。
我会像这样重写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
运算符将尝试从string
转换为ExceptionFld
,注意转换将失败,然后t将为null。
我不确定您的GetHashCode
有关性能或哈希码分发的问题,但除此之外,它看起来还可行。