2016-07-06 101 views
1

我想弄清楚如何使用NHibernate做孩子 - 父母關係。 我有兩個班級Foo和Bar。 Foo擁有一系列酒吧和酒吧,可參考家長Foo。使用NHibernate的孩子 - 父母關係

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(); 
      } 

當調用Save(foo)方法時,我有一個異常「無效投射(檢查您的映射屬性類型不匹配); 「Test.Foo的設置者」 使用iinere異常:「」無法強制轉換對象類型「」NHibernate.Collection.Generic.PersistentGenericSet 1[Test.Bar]\" к типу \"System.Collections.Generic.List 1 [Test.Bar] \「」。

我在做什麼錯了?

+1

使用'ICollection'而不是'List' –

+0

或使用可以將''改爲'' IList'而不是'List'。 –

+1

最後但並非最不重要的是:爲了堅持也來自'Children'集合的項目,應該做一些更多的調整:在,並明確地爲」Children「項設置一個父項:'foo.Children.Add(new Bar {Description =」desc1「,Parent = foo});'。 –

回答

0

嘗試更改public virtual List<Bar> Children { get; set; }public virtual ISet<Bar> Children { get; set; }。 ISet可以在Iesi.Collections.Generic.ISet<>中找到。

你甚至可以嘗試使用IList代替List,看看它是否works.Avoid使用混凝土類集合並嘗試使用接口,以便NHibernate的可以注入自己的具體實現。

相關問題