场景
我在 DB 中有一个类别类:
CREATE TABLE [dbo].[Category](
[pk_cat_id] [int] NOT NULL,
[name] [varchar](50) NOT NULL,
[parent_cat_id] [int] NULL
CONSTRAINT [PK_Category] PRIMARY KEY NONCLUSTERED
(
[pk_cat_id] ASC
))
类别类与自身有关联。它是递归的、双向的关联(多对一和一对多)。两者都引用相同的外键列:parent_cat_id。
一个类别最多可以有一个父类别,而没有或多个子类别。
这是 Category.hbm.xml:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns ="urn:nhibernate-mapping-2.2"
assembly ="NHibernateIntro.Core"
namespace ="NHibernateIntro.Core.Domain">
<class name="Category" table="Category">
<id name="CategoryId" column="pk_cat_id">
<generator class="hilo"/>
</id>
<property name="Name" column="name" type="string" length="50" not-null="true" />
<many-to-one name="ParentCategory" class="Category" column="parent_cat_id" />
<bag name="childCategories" cascade="all-delete-orphan" inverse="true">
<key column="parent_cat_id"/>
<one-to-many class="Category"/>
</bag>
</class>
</hibernate-mapping>
这是 Category.cs:
using System;
using System.Collections.Generic;
using Iesi.Collections.Generic;
namespace NHibernateIntro.Core.Domain
{
public class Category
{
private Category parent_category;
private ISet<Category> child_Categories = new HashedSet<Category>();
public virtual int CategoryId { get; set; }
public virtual string Name { get; set; }
public Category() { }
public Category( string cat_name )
{
Name = cat_name;
}
public virtual Category ParentCategory
{
get
{
if (parent_category == null)
parent_category = new Category();
return parent_category;
}
set{ parent_category = value; }
}
public virtual ISet<Category> childCategories
{
get { return child_Categories; }
set { child_Categories = value; }
}
}
}
这是主要方法:
public static void Run(ISessionFactory factory)
{
int computerId = 1;
using (ISession session = factory.OpenSession())
using (session.BeginTransaction())
{
Category computer = session.Get<Category>(computerId); // **This line causes Error(stated below)**
// Please see 'CONFUSING' tag below.
Category laptops = new Category("Laptops");
computer.childCategories.Add(laptops);
laptops.ParentCategory = computer;
session.Save(laptops);
session.Transaction.Commit();
}
}
混乱:当我调试代码时,它卡在这一行:“set { parent_category = value; }”。我很困惑,因为我分配给 Cateory 那么为什么在这里调用 parentCategory 的 setter 呢?
错误: 无效的演员表(检查您的映射是否有属性类型不匹配);NHibernateIntro.Core.Domain.Category 的设置器
内部错误:无法转换类型为1[NHibernateIntro.Core.Domain.Category]'
to type 'Iesi.Collections.Generic.ISet
“NHibernate.Collection.Generic.PersistentGenericBag 1 [NHibernateIntro.Core.Domain.Category]”的对象。
请帮助!