在fluentnhibernate中使用引用作为id

sim*_*sjo 7 nhibernate-mapping fluent-nhibernate

我有一个包含父级id的子表.这是一对一映射,但子表可能缺少值.我在绘制这个问题时遇到了问题而没有出现错误...我尝试了几件事; 映射相同的列,具有不同的属性等.

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..

制图

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");
Run Code Online (Sandbox Code Playgroud)

我希望子类不具有不同的Id字段,而只是对父项的引用,因为永远不会有没有父项的子项.但是,在数据库中,我只想存储父级的id.

我有什么想法可以做到这一点?

sim*_*sjo 5

以下作品:

Id(x => x.Parent.Id).Column("MemberID");
References(x => x.Parent).Column("MemberID").ReadOnly();
Run Code Online (Sandbox Code Playgroud)

ReadOnly对于引用非常重要,不会出现异常

编辑:不是那么简单......

我的子类仍然调用了Id属性.似乎Parent.Id的Id引用混淆了nhibernate,它试图调用child.Id.我把以下内容添加到了孩子身上,现在它似乎工作了..虽然这是一个非常丑陋的黑客.

public virtual int Id {
    get { return Parent.Id; }
    set { Debug.Assert(value == Parent.Id); }
}
Run Code Online (Sandbox Code Playgroud)