I'm building a blog/CMS system (for fun, I know there are a ton out there I could use).
I have a simple Tag entity that only has an Id (int) and a TagName (string) property. I'd like to configure nHibernate such that I can do something like:
var tag1 = Tag.CreateTag("duplicate tag test"); // Id=0 at this point
var tag2 = Tag.CreateTag("duplicate tag test"); // Id=0 at this point
TagRepository.Save(tag1); // tag1.Id is non-zero
TagRepository.Save(tag2); // tag2.Id should be the same as tag1.Id at this point, but it's not
Assert.AreEqual(tag1, tag2);
I envision Save(Tag) doing something like a look-up, and if the tag already exists, somehow replace tag2 with tag1's values. nHibernate works some magic that modifies the parameter's properties even though it's not passed as an out parameter. Can someone tell me what's happneing here and how to fix ths method to do what I want? I'm trying to avoid having to use the out keyword on the tag parameter.
public override void Save(Tag tag)
{
Tag existingTag = GetByTagName(tag.TagName);
if (null == existingTag)
{
using (ISession session = NHibernateHelper.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.SaveOrUpdate(tag);
transaction.Commit();
}
}
else
{
tag = existingTag; // obviously doesn't impact the caller
}
}