views:

42

answers:

1

I have a Person class which has a Tags property

public virtual System.Collections.Generic.List<Tag> Tags { get; set; }

which contains a collection of Tag class objects.

Given the system design, the instance of the Person class is created initially and then at a later time the user can add tags to a Person.

Being new to NHibernate I can figure out how to add one or more tags to the existing person object. Do I need to retrieve the Person object then Add() one or more new Tag objects? There may also already be Tag objects in the List.

Same question related to removing an existing Tag object in the Tags collection.

Thanks

+1  A: 

If the Tag knows which person it belongs to you could do:

var person = session.Load<Person>(id);
var tag = new Tag() { Person = person; /* stuff */ };
session.Save(tag);

session.Flush();

This should avoid doing a query on person.

I also think you'll need to change Tags to IList.


Edit:

Moved other example... I don't think it would avoid a select query.

var person = session.Load<Person>(id);
person.Tags.Add(new Tag() { /* stuff */ };

session.Flush();

I'm not sure if accessing Tags will force the object to be instantiated?

eyston
Not sure if this is answering your question. If you can add some specifics I can clarify.
eyston
I was going down the path of your edited version. Let me do some more testing. Thanks.
ChrisP
I think the two things you want to consider are whether to have a bidirectional / unidirectional relationship, and in what context you will be adding tags to person (eg. is the person loaded? do you want to load?). The documentation has a lot of parent/child relationships to look at: http://www.nhforge.org/doc/nh/en/index.html#example-parentchild (section 19). The nice thing about session.Load is that it returns a proxy that only gets fetched if it needs to.
eyston