views:

296

answers:

1

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
        }
    }
+1  A: 

I don't think your reference to 'out parameter' makes sense. The object is still the same instance, but NH has updated the ID to the generated one when saved.

I think you just have to fetch the tag first as you are doing in your example. If you want the caller to see the correct id do

tag.id = existingTag.id;

I think your question relates to parameters and how they are handled and not to NHibernate. Read this article to get a good grounding in how this stuff works.

nickd