How can I get the following test to pass with NHibernate?
I thought it was enough to simply override Equals and GetHashCode in the entity class for this to work the way I want it to. Obviously for "Point" objects, which are quite trivial, it's silly to persist multiple rows for identical coordinates. I have two point objects that have identical coordinates, and I want them to only persist to one row in the database.
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
Where my point class looks something like this:
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;
}
}