我不明白为什么NHibernate返回错误的子对象列表。
我有两个表的数据库:类别和产品。
产品具有外键,即类别ID。
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
我究竟做错了什么?
最佳答案
答案在这里:收集键必须映射到包含对父项的引用的列。
调整后的集合映射(请参见<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必须在其中搜索参考的地方关于c# - NHibernate返回错误的对象列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22186618/