摘要:父类和子类。父母和孩子之间的一对一关系。父级具有引用子级主键的FK属性。代码如下:
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; }
}
具有以下映射:
父映射
Id(x => x.NHTestParentId);
Map(x => x.ParentName);
Map(x => x.ChildId);
References(x => x.ChildRef, "ChildId").Cascade.All();
Id(x => x.NHTestChildId);
Map(x => x.ChildName);
如果我做了类似(伪代码)的事情。。。
HTestParent parent = new NHTestParent();
parent.ParentName = "Parent 1";
parent.ChildRef.ChildName = "Child 1";
nhibernateSession.SaveOrUpdate(aParent);
Commit;
如果我按以下方式更改父“References”行(即提供我所指向的子属性的名称):
References(x => x.ChildRef, "ChildId").PropertyRef("NHTestChildId").Cascade.All();
我得到错误:“无法解析属性:NHTestChildId”
因此,我尝试了“HasOne()”引用设置,如下所示:
HasOne<NHTestChild>(x => x.ChildRef).ForeignKey("ChildId").Cascade.All().Fetch.Join();
在这种安排下,save可以工作(db中的数据是所需的),但是加载无法找到子实体。检查Nhibernate生成的SQL表明Nhibernate假设父级的主键是指向子级的链接(即,load join条件是“parent.NHTestParentId=child.NHTestChildId”)。我指定的'ForeignKey'似乎被忽略了-如果事实上我可以设置任何值(甚至一个不存在的字段)并且没有发生错误-连接总是失败并且没有返回子级。
我在上面尝试了一些细微的变化。似乎这应该是一件简单的事情。有什么想法吗?