开发者

Automatically update both end of a one to many relationship with NHibernate

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 correctl开发者_StackOverflow社区y, 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!


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.


@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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜