2014-03-05 107 views
2

我不明白爲什麼NHibernate返回一個錯誤的子對象列表。 我有兩個表的數據庫:類別和產品。 產品有一個外鍵,類別的Id。NHibernate返回錯誤的對象列表

Category table       Product table 
Id | Name | Description   Id | Name | Description | Category_Id 

映射:

<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
        assembly="NHDemo" 
        namespace="NHDemo"> 
    <class name="Category"> 
    <id name="Id"> 
     <generator class="native" /> 
    </id> 
    <property name="Name" /> 
    <property name="Description" /> 
    <set name="Products" inverse="true" lazy="true" > 
     <key column="Id"/> 
     <one-to-many class="Product"/> 
    </set> 
    </class> 
</hibernate-mapping> 

和:

<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
        assembly="NHDemo" 
        namespace="NHDemo"> 
    <class name="Product"> 
    <id name="Id"> 
     <generator class="native" /> 
    </id> 
    <property name="Name"/> 
    <property name="Description"/> 
    <many-to-one name="Category" class="Category" fetch="select"> 
     <column name="Category_Id" not-null="true" /> 
    </many-to-one> 
    </class> 
</hibernate-mapping> 

C#代碼:

namespace NHDemo 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var cfg = new Configuration(); 
      cfg.Configure(); 
      var sessionFactory = cfg.BuildSessionFactory(); 
      using(var session = sessionFactory.OpenSession()) 
      using (var tx = session.BeginTransaction()) 
      { 
       var results = session.CreateCriteria<Category>().List<Category>(); 
       foreach (var category in results) 
       { 
        Console.WriteLine(category.Name); 
        foreach (var product in category.Products) 
         Console.WriteLine(product.Name); 
       } 
      } 
     } 
    } 

    public class Product 
    { 
     public virtual int Id { get; set; } 
     public virtual string Name { get; set; } 
     public virtual string Description { get; set; } 
     public virtual Category Category { get; set; } 
    } 

    public class Category 
    { 
     private ISet<Product> products; 
     public virtual int Id { get; set; } 
     public virtual string Name { get; set; } 
     public virtual string Description { get; set; } 
     public virtual ISet<Product> Products 
     { 
      get { return products; } 
      set { products = value; } 
     } 
    } 
} 

意思是說我有兩個類別和四個產品,因爲他們有聯繫,我期待的結果:

Category1 
Product1 
Product2 
Category2 
Product3 
Product4 

,但我發現結果:

Category1 
Product1 
Category2 
Product2 

我到底做錯了什麼?

回答

2

答案就在這裏:收集關鍵必須映射到包含參考

調整集合映射(參見<key>屬性值)

<set name="Products" inverse="true" lazy="true" > 
    <key column="Category_Id"/>     <--- here is the change 
    <one-to-many class="Product"/> 
</set> 

所以Category_Id是地方,在那裏必須NHibernte搜索參考