-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: GetHashCode() before and after persistence...
PostPosted: Mon Mar 27, 2006 1:33 am 
Beginner
Beginner

Joined: Thu Dec 08, 2005 6:49 pm
Posts: 49
I seem to be in the impossible situation whereby I need my objects to return the same hashcode before they're saved, after they're saved and when they're loaded in a new session.

I currently have the following (inadequate) GetHashCode() implementation:

Code:
public override int GetHashCode()
{
   if (_ID == Guid.Empty)
      return base.GetHashCode();

   return _ID.GetHashCode();
}


This will clearly return a different value before and after object persistence. This is a problem because my object model is rich with HashedSet properties which require objects to have an immutable hashcode.

The following example should illustrate my problem:

Code:
Blog b = new Blog();
Post p = new Post();
b.Posts.Add(p);
Console.WriteLine(b.Posts.Contains(p)); //True
Save(b);
Console.WriteLine(b.Posts.Contains(p)); //False


Is my only option to move to assigned IDs that are created in the constructor of my domain objects? I seem to remember reading somewhere that there are implications with using assigned IDs when it comes to NH knowing if child objects have been previously saved.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Mar 27, 2006 6:37 am 
Contributor
Contributor

Joined: Wed May 11, 2005 4:59 pm
Posts: 1766
Location: Prague, Czech Republic
You should try and make your GetHashCode depend on something other than the database ID. Ideally, both Equals and GetHashCode should be based on a "business key" - some combination of columns that uniquely identifies an entity and changes only rarely.

Another option is to first call Save on the object (to have its id generated) and only then add it to collections.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.