views:

34

answers:

2

Hello,

It is of a newby question, so sorry in advance.

I'm using fluent NHibernate and get a strange behavior on it.

I have two classes that look like that (simplified) :

public class Group
{
    public virtual int Id{get;protected set;}
    public virtual String Name{get;set;}
    public virtual List<Person> Persons {get; protected set;}
}

public class Person
{
    public virtual int Id{get;protected set;}
    public virtual String Name{get;set}
    public virtual Group Group {get;set;}
}

And the mappings Group:

Id(x=>x.Id)
Map(x=>x.Name)
HasMany(x=>x.Persons).Cascade.All.Inverse()

Person:

Id(x=>x.Id)
Map(x=>x.Name)
References(x=>x.Group)

Now, in my code I want to move a person that I have to another group. Since it is a relationship, I thought I could simply do

myPerson.Group = anotherGroup;
_mySession.SaveOrUpdate(myPerson);
_mySession.Flush()

If I do that, the database is updated correctly, but if I try to look in the list of persons of the object "anotherGroup" I don't see the object "myPerson", which is still in the old group's persons list.

So, is there a way to tell NH to reload the list, or to make it update always.

The only workaround which I have found now is this :

myPerson.Group.Persons.Remove(myPerson);
anotherGroup.Persons.Add(myPerson);
myPerson.Group = anotherGroup;
_mySession.Flush()

But I find it a bit dirty...

Any idea on what I'm doing wrong? Thanks!

+3  A: 

Use helper methods to simplify this; on group you'd want something along the lines of:

RemovePerson(person)
AddPerson(person)

You may find this article helpful for additional guidance: Strengthening your domain: Encapsulated collections.

DanP
Well, actually it's what I'm doing now, I've not shown them here for simplification, but I thought NH would do that job for me, won't he?Thanks for the link, very interesting.
Gimly
@Gimly - unfortunately not, mantaining those relationships is your responsibility.
DanP
Any hints on why this is the case? I think that in Linq2Sql those relationships were automatic. Will future versions change that?
Gimly
@Gimly - I'm not sure to be honest, you might try posting in the nhusers group for further info.
DanP
+2  A: 

@Gimly the relationships in L2S are automatic because it uses custom collections (NHibernate works with standard interfaces and can persist a collection after you instantiate it as, for example, List). There was, however, some informal talk on how to improve that, but nothing's on the trunk, as it has a very low priority, given the easy workaround (the answer above)

Diego Mijelshon
@Diego - I was hoping you or Fabio would chime in, thanks for the confirmation
DanP
Thanks for the insight, always interesting to know the reasons behind a choice like that.
Gimly
Anyway, don't take my words as canonical, I'm just an enthusiastic user :-)
Diego Mijelshon