NHibernate-访问对象';s通过id或对象引用的父对象

NHibernate-访问对象';s通过id或对象引用的父对象,nhibernate,fluent-nhibernate,mapping,one-to-many,Nhibernate,Fluent Nhibernate,Mapping,One To Many,我有以下课程: public class Parent { public virtual int ParentId { get; set; } public virtual string Name { get; set; } public virtual ICollection<Child> Children { get; set; } } public class Child { public virtual int ChildId { get;

我有以下课程:

public class Parent
{
    public virtual int ParentId { get; set; }
    public virtual string Name { get; set; }
    public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
    public virtual int ChildId { get; set; }
    public virtual string Name { get; set; }
    //public virtual int ParentId { get; set; }
    public virtual Parent Parent { get; set; }
}
也就是说,我希望能够通过Child.ParentId属性将父对象附加到子对象,同时仍然能够通过Child.Parent属性访问父对象。例如:

// i currently have to do the following in order to link the child with
// the parent when I update an existing Child instance (ParentService() and 
// ChildService() are service classes that sit between my applications and
// NHibernate).
var parentService = new ParentService();
var parent = parentService.GetById(1);
var child = new Child() { ChildId = 2, Parent = parent, Name = "New Name" };
var childService = new ChildService();
childService.Save(child);

// in a different project, i access the Parent object via the child's
// Parent property
var childService = new ChildService();
var child = childService.GetById(2);
Console.WriteLine(child.Parent.Name);


// i want to do this instead
var child = new Child() { Id = 2, ParentId = 1, Name = "New Name" };
var childService = new ChildService();
childService.Save(child);
Console.WriteLine(child.Id); // 11

// [ ... ]

var childService = new ChildService();
var child = childService.GetById(2);
Console.WriteLine(child.Parent.Name);
如何更改映射以实现这一点?蒂亚


拉尔夫·汤普森(Ralf Thompson)

这不是NHibernate的正确用法

要获取父级的Id,请使用:

var parentId = child.Parent.Id; //this does not cause loading
要按Id设置父项,请使用

child.Parent = session.Load<Parent>(parentId); //this never goes to the DB either
child.Parent=session.Load(parentId)//这也不属于DB

这不是NHibernate的正确用法

要获取父级的Id,请使用:

var parentId = child.Parent.Id; //this does not cause loading
要按Id设置父项,请使用

child.Parent = session.Load<Parent>(parentId); //this never goes to the DB either
child.Parent=session.Load(parentId)//这也不属于DB

这正好符合我的目的。我将不得不玩它,看看我如何使用它。Thanx.那正好符合我的目的。我将不得不玩它,看看我如何使用它。塔克斯。