シナリオ
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
))
カテゴリ クラスはそれ自体に関連付けられています。これは、再帰的な双方向の関連付け (多対 1 および 1 対多) です。どちらも同じ外部キー列 (parent_cat_id) を参照しています。
カテゴリは、最大で 1 つの親カテゴリを持つことができ、子カテゴリを持たないか、または複数持つことができます。
これは 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; }
}
}
}
これは Main メソッドです。
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;}」という行でスタックしました。私はカテゴリに割り当てているので混乱していますが、なぜparentCategoryのセッターがここで呼び出されているのですか?
エラー: キャストが無効です (プロパティ タイプの不一致についてマッピングを確認してください)。NHibernateIntro.Core.Domain.Category のセッター
内部エラー:1[NHibernateIntro.Core.Domain.Category]'
to type 'Iesi.Collections.Generic.ISet
タイプ「NHibernate.Collection.Generic.PersistentGenericBag 1[NHibernateIntro.Core.Domain.Category]」のオブジェクトをキャストできません。
親切に助けて!!