NHibernate - accessing an object's parent via id or object reference
I have the following classes:
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; }
}
These classes map to corresponding tables in the database in a one-to-many relationship. In my mapping classes, I do the following:
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();
}
}
What I need to be able to do is expose (uncomment the line in the class definition above) the ParentId property in the Child class so that I can do the following:
var child = new Child();
child.ParentId = 1;
That is, I want to be able to attach the Parent to the Child via the child.ParentId property while still being able to access the Parent via the child.Parent property. E.g.,
// 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, Pa开发者_如何学编程rentId = 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);
How would I change the mappings to make that happen? TIA,
Ralf Thompson
That's not a correct usage of NHibernate.
To get the Id of the parent use:
var parentId = child.Parent.Id; //this does not cause loading
To set the parent by Id, use
child.Parent = session.Load<Parent>(parentId); //this never goes to the DB either
精彩评论