我有一个实体类,像这样(省略了很多内容):
class Parent
{
private readonly Iesi.Collections.Generic.ISet<Child> children =
new Iesi.Collections.Generic.HashedSet<Child>();
public virtual void AddChild(Child child)
{
if (!this.children.Contains(child))
{
this.children.Add(child);
child.Parent = this;
}
}
public virtual void RemoveChild(Child child)
{
if (this.children.Contains(child))
{
child.Parent = null;
this.children.Remove(child);
}
}
}
然而,当我试图移除一个子元素时,if
语句的结果却是false
。因此,我在if
语句上设置了断点,并评估了某些表达式:
this.children.Contains(child) => false
this.children.ToList()[0].Equals(child) => true
this.children.ToList()[0].GetHashCode() => 1095838920
child.GetHashCode() => 1095838920
我的理解是如果
GetHashCode
返回相同的值,它会检查Equals
。那么为什么Contains
返回false呢?
我的
Parent
和Child
实体都继承自一个公共的基类Entity
,该基类是NHibernate 3.0 Cookbook第25页上的通用实体基类的非泛型版本。以下是我的基类:public class Entity : IEntity
{
public virtual Guid Id { get; private set; }
public override bool Equals(object obj)
{
return Equals(obj as Entity);
}
private static bool isTransient(Entity obj)
{
return obj != null &&
Equals(obj.Id, Guid.Empty);
}
private Type getUnproxiedType()
{
return GetType();
}
public virtual bool Equals(Entity other)
{
if (other == null)
return false;
if (ReferenceEquals(this, other))
return true;
if (!isTransient(this) &&
!isTransient(other) &&
Equals(Id, other.Id))
{
var otherType = other.getUnproxiedType();
var thisType = getUnproxiedType();
return thisType.IsAssignableFrom(otherType) ||
otherType.IsAssignableFrom(thisType);
}
return false;
}
public override int GetHashCode()
{
if (Equals(Id, Guid.Empty))
return base.GetHashCode();
return Id.GetHashCode();
}
}
经过进一步调查,我感觉类似以下情况正在发生:
- 调用
parent.AddChild(child)
- 保存到数据库,导致生成了
child.Id
- 调用
parent.RemoveChild(child)
GetHashCode()
。这是我的程序中的一个错误 - 我应该在步骤2和3之间重新加载
parent
。尽管如此,我认为还有更根本性的问题。
private Iesi.Collections.Generic.HashedSet<Child> children = new Iesi.Collections.Generic.HashedSet<Child>();
。 - L.B