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
這只是可以爲我的目的。我將不得不玩,看看我可以如何使用它。感謝名單。 – 2011-03-22 20:48:10