我有以下类和相关的映射(Fluent NHibernate):
public class Category
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual Category ParentCategory { get; set; }
public virtual IList<Category> ChildCategories { get; set; }
}
映射:
public class CategoryMap : ClassMap<Category>
{
public CategoryMap()
{
Table("Categories");
Id(x => x.Id).Column("Id").CustomType("Int32").Access.Property()
.CustomSqlType("int").Not.Nullable().Precision(10)
.GeneratedBy.Identity();
Map(x => x.Description).Column("Description").Nullable()
.Generated.Never().CustomType(typeof (string)).Access
.Property().Length(250);
Map(x => x.Name).Not.Nullable().Generated.Never().CustomType("string")
.Access.Property().Column("Name").Length(50);
References(x => x.ParentCategory).Column("ParentCategoryId");
HasMany(x => x.ChildCategories).KeyColumn("ParentCategoryId").Inverse()
.AsBag().Fetch.Select();
}
}
我创建两个Category
对象如下:
var c = new Category
{
Name = "Ebooks",
Description = "Contains awz, mobi, pdf, epub and other
electronic books"
};
var cc = new Category
{
Name = "Kindle Books",
Description = "Contains Kindle ebook reader format books
(awz, mobi)",
ParentCategory = c
};
session.SaveOrUpdate(c);
session.SaveOrUpdate(cc);
当我尝试访问保存的对象时:
var c = session.Load<Category>(1);
var cc = c.ChildCategories;
c
包含Category
对象Id
为 1 但其ChildCategories
属性为null
.
我做错了什么?
PS:-这是我的第一次实验,NHibernate
等等Fluent NHibernate
。
编辑:-以下内容有效。我需要先关闭会话,然后再打开它进行阅读。否则,它只是从内存中读取,正如@Holf 指出我需要添加Child Category
的Category
那样:
c.ChilCategories.Add(cc);
我只是做了如下:
var session = sf.OpenSession();
CreateCategory(session);//ADDED TWO CATEGORIES EBooks, Kindle Ebooks
session.Close();
session = sf.OpenSession();
FetchCategories(session);//READ CATEGORY EBooks AND ASSOCIATED CHILDREN
session.Close();