【问题标题】:NHibernate 3.0 beta1 Bidirectional One-To-Many Cannot Add Child ObjectNHibernate 3.0 beta1 双向一对多无法添加子对象
【发布时间】:2010-10-13 23:22:22
【问题描述】:

简而言之,问题是,当没有显式设置子对象的父属性将子对象添加到父对象的集合属性时,插入会失败。举个例子:

注意:我使用的是 NHibernate 3.0 beta1。

示例:产品类别情景:

(1) 数据库架构:

  1. 类别(ID、名称)
  2. 产品(ID、名称、价格、CategoryId)

(2) 领域模型的 C# 代码

public class Category
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<Product> Products { get; private set; }
}    

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

(3) 映射

<class name="Category" table="Category">
  <id name="Id" column="Id">
    <generator class="identity" />
  </id>
  <property name="Name" />
  <bag name="Products" inverse="true" cascade="all">
    <key column="CategoryId" />
    <one-to-many class="Core.Product"/>
  </bag>
</class>

<class name="Product" table="Product">
  <id name="Id" column="Id">
    <generator class="identity" />
  </id>

  <property name="Name" />
  <property name="Price" />
  <many-to-one name="Category" column="CategoryId" />
</class>

(4) 调用代码

using (var session = sessionFactory.OpenSession())
{
    Category category = session.Query<Category>().FirstOrDefault();
    Product product = new Product
    {
        Name = "test",
        Price = 50
    };
    category.Products.Add(product);
    // Here, the p.Category is null, but it should NOT be null
    // And if now I commit the changes the the database,
    // And exception will be thrown: Cann't insert null to column CategoryId
}

category.Products.Add(product)被执行时,product.Category应该是对象category!如果我将product.Category 显式设置为类别,则提交操作将成功。 为什么这个? NHibernate 3.0 beta1 或者其他的bug?

【问题讨论】:

标签: .net nhibernate nhibernate-mapping one-to-many nhibernate-3


【解决方案1】:

这与记录的完全一样。

6.4. One-To-Many Associations

NHibernate 不会为您设置product.Category。避免忘记这一点的常用方法是向 category 添加一个 AddProduct 方法,该方法将产品添加到 Products 集合并设置 Category 属性。

【讨论】:

  • 那太糟糕了。我认为 Entity Framework 在这一点上做得更好。 BTW:我没有在文档中找到说NHibernate will not set the product.Category的句子,你能帮我复制一下吗,谢谢:)
猜你喜欢
  • 2014-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-03
  • 2010-10-08
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多