views:

10

answers:

1

I have a child table containing an id to the parent. This is a one to one mapping, but the child table might be missing values. I'm having problems mapping this without getting an error though... I've tried several things; mapping the same column, having distinct properties etc..

Parent table
  int id

Child table
  int parentid

Parent class
  int id

Child class
  Parent parent // note I'm referencing parent, not using an int id..


Child mapping
  Id(x => x.Parent)
    .Column("parentid"); // fails

    Id(x => x.Parent.Id)
    .Column("parentid"); // fails

  References(x => x.Parent)
    .Column("parentid"); // fails - missing id

  // Adding an id field in addition to parent for child class (id is then the same as parent.id)
  // fails on save
  Id( x => x.Id ) 
    .Column("parentid");
  References(x => x.Parent)
    .Column("parentid");

I would like the child class not to have a distinct Id field, but rather only a reference to parent as there can never be a child without a parent. In the database however, I want to just store the parent's id.

Any ideas how I might do this?

A: 

The following works:

Id(x => x.Parent.Id).Column("MemberID");
References(x => x.Parent).Column("MemberID").ReadOnly();

The ReadOnly for the reference is important to not get an exception

EDIT: Wasn't so simple...

My child class still had the Id property being called. Seems the Id reference for Parent.Id confuses nhibernate, and it tries to call child.Id instead. I added the following to child, and now it seems to work.. A pretty ugly hack though.

public virtual int Id {
    get { return Parent.Id; }
    set { Debug.Assert(value == Parent.Id); }
}
simendsjo

related questions