views:

170

answers:

1

Summary: Parent and Child class. One to one relationship between the Parent and Child. Parent has a FK property which references the primary key of the Child. Code as follows:

  public class NHTestParent
  {
    public virtual Guid NHTestParentId { get; set; }
    public virtual Guid ChildId
    {
      get
      {
        return ChildRef.NHTestChildId;
      }
      set { }
    }
    public virtual string ParentName { get; set; }

    protected NHTestChild _childRef;
    public virtual NHTestChild ChildRef
    {
      get
      {
        if (_childRef == null)
          _childRef = new NHTestChild();
        return _childRef;
      }
      set
      {
        _childRef = value;
      }
    }
  }    

  public class NHTestChild
  {
    public virtual Guid NHTestChildId { get; set; }
    public virtual string ChildName { get; set; }
  }

With the following Fluent mappings:

Parent Mapping

  Id(x => x.NHTestParentId);
  Map(x => x.ParentName);
  Map(x => x.ChildId);
  References(x => x.ChildRef, "ChildId").Cascade.All();

Child Mapping:

  Id(x => x.NHTestChildId);
  Map(x => x.ChildName);

If I do something like (pseudo code) ...

HTestParent parent = new NHTestParent();
parent.ParentName = "Parent 1";
parent.ChildRef.ChildName = "Child 1";
nhibernateSession.SaveOrUpdate(aParent);
Commit;

... I get an error: "Invalid index 3 for this SqlParameterCollection with Count=3"

If I change the parent 'References' line as follows (i.e. provide the name of the child property I'm pointing at):

References(x => x.ChildRef, "ChildId").PropertyRef("NHTestChildId").Cascade.All();

I get the error: "Unable to resolve property: NHTestChildId" So, I tried the 'HasOne()' reference setting, as follows:

HasOne<NHTestChild>(x => x.ChildRef).ForeignKey("ChildId").Cascade.All().Fetch.Join();

In this arrangement the save works (and data in db is as wanted), but loading fails to find the child entity. Inspecting the SQL Nhibernate produces shows me that NHibernate is assuming the Primary key of the parent is the link to the child (i.e. load join condition is "parent.NHTestParentId = child.NHTestChildId). The 'ForeignKey' I specified appears to be ignored - if fact I can set any value (even a non-existance field) and no error occurs - the join just always fails and no child is returned.

I've tried a number of slight variations on the above. It seems like it should be a simple thing to achieve. Any ideas?

+2  A: 

you are mapping the same column twice, and that is not allowed. Remove the following from the parent class

Map(x => x.ChildId);

see also http://stackoverflow.com/questions/2298026/indexoutofrangeexception-deep-in-the-bowels-of-nhibernate/2311256#2311256

Jaguar
Thanks. That was exactly the problem. After a 1/2 day of trying every variation of mapping I could think of, it come down to removing one line of code. Pity NHibernate (or Fluent) doesn't recognize the dual mapping of a column and throw a (meaningful) error.
Trevor