2011-03-21 79 views
0

我有以下的类访问对象的父:NHibernate的 - 通过ID或对象引用

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(); 
    } 
} 

我需要能够做的是暴露(取消注释在上面的类定义的线)的ParentId属性的子类,这样我可以做以下:

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

也就是说,我希望能够通过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); 

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

Ralf Thompson

回答

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 
+0

这只是可以为我的目的。我将不得不玩,看看我可以如何使用它。感谢名单。 – 2011-03-22 20:48:10