NHibernate를 사용하여 자식 - 부모 관계를 만드는 방법을 알아 내려고하고 있습니다. 두 가지 Foo와 Bar 클래스가 있습니다. Foo에는 Bars and Bar 컬렉션이 있으며 부모 Foo에 대한 참조가 있습니다.NHibernate를 사용하는 Child-Parent 관계
public class Foo
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual List<Bar> Children { get; set; }
}
public class Bar
{
public virtual int Id { get; set; }
public virtual string Description { get; set; }
public virtual Foo Parent { get; set; }
}
이 클래스의 매핑은 다음과 같습니다
가<class name="Foo" table="foos">
<id name="Id" column="id">
<generator class="identity"/>
</id>
<property name="Name" column="name" />
<set name="Children" inverse="true" lazy="true">
<key column="fooId"/>
<one-to-many class="Bar"/>
</set>
</class>
<class name="Bar" table="bars">
<id name="Id" column="id">
<generator class="identity"/>
</id>
<property name="Description" column="description" />
<many-to-one name="Parent" column="fooId"/>
</class>
이것은 sesion 공장 제작 : 여기
if (_sessionFactory == null)
{
var configuration = new Configuration();
configuration.Configure();
configuration.AddAssembly(typeof(Foo).Assembly);
_sessionFactory = configuration.BuildSessionFactory();
}
그리고 내가 새로운 푸 추가 해요 방법은 다음과 같습니다
Foo foo = new Foo { Name = "name1" };
foo.Children = new List<Bar>();
foo.Children.Add(new Bar { Description = "desc1" });
foo.Children.Add(new Bar { Description = "desc2" });
using (ISession session = NHibirnateHelper.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(foo);
transaction.Commit();
}
저장 (foo) 메소드를 호출 할 때 예외 "잘못된 캐스트 (속성 유형 불일치에 대한 매핑 확인); "Test.Foo의 setter" iinere 예외 : ""객체 유형을 변환 할 수 없습니다 \ "NHibernate.Collection.Generic.PersistentGenericSet 1[Test.Bar]\" к типу \"System.Collections.Generic.List
1 [Test.Bar] \" ".
내가 뭘 잘못하고있어?
'List' 대신'ICollection'을 사용하십시오. –
또는 '을' '으로 변경하고' IList' 대신'List'를 사용합니다. –
그리고 마지막으로 중요한 것은'Children' 콜렉션의 항목을 유지하기 위해서'''을 호출하고'Children' 항목에 대한 부모를 명시 적으로 설정합니다 :'foo.Children.Add (new Bar {Description ="desc1 ", Parent = foo}); –