NHibernate - 通过id或对象引用访问对象的父级

时间:2011-03-21 20:52:45

标签: 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; set; }
    public virtual string Name { get; set; }
    //public virtual int ParentId { get; set; }
    public virtual Parent Parent { get; set; }
}

这些类以一对多的关系映射到数据库中的相应表。在我的映射类中,我执行以下操作:

using FluentNHibernate.Mapping;
public partial class ParentMap : ClassMap<Parent>
{
    public ParentMap()
    {
        Id(p => p.ParentId).Column.("PARENT_ID").GeneratedBy.Native();
        Map(p => p.Name).Column("PARENT_NAME").Not.Nullable();
        HasMany<Child>(p => p.Children).Cascade.All().LazyLoad().Inverse().AsSet();
    }
}

public partial class ChildMap : ClassMap<Child>
{
    public ChildMap()
    {
        Id(c => c.ChildId).Column("CHILD_ID").GeneratedBy.Native();
        Map(c => c.Name).Column("CHILD_NAME").Not.Nullable();
        References<Parent>(c => x.Parent).Column("PARENT_ID").Not.LazyLoad().Not.Nullable();
    }
}

我需要做的是公开(取消注释上面类定义中的行)Child类中的ParentId属性,以便我可以执行以下操作:

var child = new Child();
child.ParentId = 1;

也就是说,我希望能够通过child.ParentId属性将Parent附加到Child,同时仍然可以通过child.Parent属性访问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);

如何更改映射以实现此目的? TIA,

拉尔夫汤普森

1 个答案:

答案 0 :(得分:4)

这不是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