Ciel
Ciel

Reputation: 17752

Fluent nHibernate, Reverse One-One Property

I thought this would be pretty simple, but it is proving a bit more frustrating than I anticipated.

Given a structure similar to this ...

class Template {
  public virtual int Id { get; set; }
  public virtual Attached Attached { get; set; }
}

class Attached {
 public virtual int Id { get; set; }
 public virtual Template Template { get; set; }
}

I want the table structure to look like this.

Table - Template

Id

Table - Attached

Id - TemplateId

So I set up my mapping ...

class TemplateMap : ClassMap<Template> {
  TemplateMap(){
    HasOne(x => x.Attached).Cascade.All();
  Table("Templates");
  }
}
class AttachedMap : ClassMap<Attached> {
  AttachedMap(){
    References(x => x.Template).Cascade.All().Column("TemplateId");
    Table("Attached");
  }
}

then I create a new Template

var tmpl = new Template {
  Attached = new Attached {
    // ... 
  }
};

session.SaveOrUpdate(tmpl);
transaction.Commit();

But my TemplateId in the Attached table still comes out Null. Any ideas?

Upvotes: 1

Views: 1082

Answers (1)

Cole W
Cole W

Reputation: 15303

I think both sides of the relationship here need to be a one to one. Also you'll need to specify on one side of the relationship that the id is generated foreignly.

Read the following 2 articles if you need more detail:
link1
link2

Edit:
Here is an example in Fluent of what I'm talking about and also what they talked about in link1:
Fluent Example

Upvotes: 1

Related Questions