tags:

views:

19

answers:

2

I have two objects that reference each other. From a purely schema perspective, object one could have many instances of object two that reference it, but the business logic specifies that each instance of object 2 will reference a unique instance of object one and vice versa.

Example:

public class Object1 {
    public Guid Id {get;set;}
    public Object2 Object2 {get;set;}

    public Object1ClassMap : ClassMap<Object1> 
    {
        // ...
        References<Object2>(x=>x.Object2)
            .Column("Object2Id")
            .Cascade.SaveUpdate()
            .Not.LazyLoad();
    }
}

public class Object2 {
    public Guid Id {get;set;}
    public Object1 Object2 {get;set;}

    public Object2ClassMap : ClassMap<Object1> 
    {
        // ...
        References<Object1>(x=>x.Object1)
            .Column("Object1Id")
            .Cascade.SaveUpdate()
            .Not.LazyLoad();
    }
}

When I do the following:

instanceOfObject1.Object2 = instanceOfObject2

I would expect NHibernate to detect the back reference and automatically do

instanceOfObject2.Object1 = instanceOfObject1

for me, but this doesn't happen. I have to manually update in both directions. Any way to avoid this?

A: 

You need to think about it in terms of POCO objects not Database relationships. A relationship between obj1 and obj2 does not assume an inverse relationship. To make a strong bi-directional relationship you do have to manually set the relationships. You might find it easier to write a couple of set function that does something like this:

public class Object1(){
  public Object2 Object2 { get; internal set; }

  public void SetObject2(Object2 obj2){
    Object2 = obj2;
    obj2.Object1 = this;
  }
}

public class Object2(){
  public Object1 Object1 { get; internal set; }

  public void SetObject1(Object1 obj1){
    obj1.SetObject2(this);
  }
}
Michael Gattuso
A: 

From what you describe you need an one-to-one relationship between your objects. I cannot explain it better than this article does:

http://ayende.com/Blog/archive/2009/04/19/nhibernate-mapping-ltone-to-onegt.aspx

The article uses XML mappings but I am sure you will be able easily to translate it to the Fluent way.

Read as it may give you the answer you look for.

In any case you should expect NHibernate to detect the back reference after you save both objects into NHibernate's session. (As it happens in the article's example).

tolism7
I tried a one-to-one, but apparently that only works if the two share a primary key, which these do not.
Chris