Hi ,
I'm confused with PersistenceId and BusinessId behaviour when transient entity objects are persisted.
I have a persistent class with the following interface
Code:
public class Game
{
public int Id {get;set;} //persistence id
public string Name { get; set;} // business id , has to be unique
}
If you look at the following Test , this is what I want to achieve:
Code:
[Test]
public void CheckGameEquality()
{
ISession session = factory.OpenSession();
Game game1 = new Game("A Game");
Game game2 = new Game("A Game");
session.SaveOrUpdate(game1);
session.SaveOrUpdate(game2);
session.Flush();
Assert.AreEqual(1,gameRepository.GetAllGames().Count);
}
I would like that the session recognizes that these two transient object that do not have a persistence ID are the same. So I read that you should override Equals in my Game class to achieve that :
http://devlicio.us/blogs/billy_mccafferty/archive/2007/04/25/using-equals-gethashcode-effectively.aspxCode:
public override bool Equals(object obj)
{
if (this == obj) return true;
Game game = obj as Game;
if (game == null) return false;
bool neitherTransient = game.persistenceId != 0 && this.persistenceId != 0;
if(neitherTransient)
{
//Compare persistence id
if(game.persistenceId == this.persistenceId)
{
return true;
}
else
{
return false;
}
}
else
{
//One or both transient , then compare business IDs
if(game.Name == Name)
{
return true;
}
else
{
return false;
}
}
}
public override int GetHashCode()
{
return (GetType().FullName + "|" + Name ).GetHashCode();
}
My test still fails , there are 2 Game Rows in the database table. The equals never gets called. I think I must be missing the plot here.
I'd be very grateful for some help.
Thanks
Hibernate version:
Nhibernate 1.2
Mapping documents:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="GameGoldTracker.Tracker" namespace="GameGoldTracker.Tracker" >
<class name="Game" table="Game" >
<id name="PersistenceId" column="Id" type="integer" >
<generator class="identity" />
</id>
<property name="name" type="string" column="Name" access="field" length="100" />
<component name="servers" class="Servers" access="field">
<bag name="list" access="field" cascade="all-delete-orphan" >
<key column="GameId" />
<one-to-many class="Server" />
</bag>
</component>
<component name="factions" class="Factions" access="field">
<bag name="list" access="field" cascade="all-delete-orphan" >
<key column="GameId"/>
<one-to-many class="Faction" />
</bag>
</component>
</class>
</hibernate-mapping>