我怎样才能通过 NHibernate 获得以下测试?
我认为只需覆盖实体类中的 Equals 和 GetHashCode 就足以让它按照我想要的方式工作。显然,对于非常微不足道的“点”对象,为相同的坐标保留多行是愚蠢的。我有两个坐标相同的点对象,我希望它们只保留到数据库中的一行。
Point p1 = new Point(1, 1, 1);
Point p2 = new Point(1, 1, 1);
Assert.AreEqual(p1, p2); //Passes
session.Save(p1);
session.Save(p2);
tx.Commit();
IList<Point> points = session.CreateCriteria<Point>()
.List<Point>();
Assert.AreEqual(1,points.Count); //FAILS
我的点课看起来像这样:
public class Point
{
public virtual Guid Id { get; set; }
public virtual double X { get; set; }
public virtual double Y { get; set; }
public virtual double Z { get; set; }
public Point(double x, double y, double z)
{
X = x; Y = y; Z = z;
}
public override bool Equals(object obj)
{
Point you = obj as Point;
if (you != null)
return you.X == X && you.Y == Y && you.Z == Z;
return false;
}
public override int GetHashCode()
{
int hash = 23;
hash = hash * 37 + X.GetHashCode();
hash = hash * 37 + Y.GetHashCode();
hash = hash * 37 + Z.GetHashCode();
return hash;
}
}