我有一个名为Category的自引用实体。 类别可以具有一个或多个子类别。一个类别也可能没有孩子。
我已经制作了实体和映射,但我一直得到这个例外。
NHibernate.TransientObjectException:object引用未保存的 瞬态实例 - 在刷新或保存之前保存瞬态实例 将属性的级联操作设置为可以创建它的东西 自动保存。
我是否在绘制映射部分时出错了?
是否可以一次保存所有父对象和子对象?
任何帮助将不胜感激。
以下是代码
POCO
public class Category
{
private ICollection<Topic> _topics;
private ICollection<Category> _childCategory;
private ICollection<Media> _media;
private Category _parentCategory;
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual bool IsActive { get; set; }
public virtual Category ParentCategory
{
get { return _parentCategory ?? (_parentCategory = new Category()); }
protected set { _parentCategory = value; }
}
public virtual ICollection<Category> ChildCategory
{
get { return _childCategory ?? (_childCategory = new List<Category>()); }
protected set { _childCategory = value; }
}
public virtual void AddChild(Category childCategory)
{
childCategory.ParentCategory = this;
}
}
映射
public class CategoryMapping : IAutoMappingOverride<Category>
{
public void Override(AutoMapping<Category> mapping)
{
mapping.Map(c => c.Name).Length(30);
mapping.Map(c => c.Description).Length(160);
mapping.References(x => x.ParentCategory)
.Cascade.None()
.Column("ParentCategoryId");
mapping.HasMany(x => x.ChildCategory)
.Inverse().Cascade.All()
.KeyColumn("ParentCategoryId");
}
}
测试 我正在创建父类和子类,并尝试一次保存所有类别。
public void CanSaveAllNewObjectGraphFromCategory() {
#region Categories and Child
var categories = new sq.Category()
{
Description = "Category1",
IsActive = true,
Name = "Categoy1"
};
var childCat = new List<sq.Category>() {
new sq.Category(){
Description = "ChildCategory1",
IsActive = true,
Name = "CCategoy1"
},
new sq.Category(){
Description = "ChildCategory2",
IsActive = true,
Name = "CCategoy2"
}
};
foreach (var item in childCat)
{
categories.AddChild(item);
}
#endregion
using (var tx = _session.BeginTransaction())
{
_catRepo.AddNewCategory(categories);
tx.Commit(); // Error occurs when commit is executed.
}
}
答案 0 :(得分:1)
您的错误消息为您提供了两个选项:
第一个选项很简单:只需在提交事务之前保存每个实例
using (var tx = _session.BeginTransaction())
{
foreach(var category in categories)
{
_session.SaveOrUpdate(category);
}
_catRepo.AddNewCategory(categories);
tx.Commit();
}
答案 1 :(得分:0)
我们需要指定参考文献的两面
public virtual void AddChild(Category childCategory)
{
childCategory.ParentCategory = this;
// add to collection as well
_childCategory.Add(childCategory);
}