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
我到底做錯了什麼?