0

つまり、問題は、子オブジェクトの親プロパティを明示的に設定せずに親オブジェクトのコレクション プロパティに子オブジェクトを追加すると、挿入が失敗することです。例を見てみましょう:

: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 などのバグ?

4

1 に答える 1

1

これは、文書化されているとおりに動作します。

6.4。1対多の関連付け

NHibernateは設定さproduct.Categoryれません。これを忘れないようにする通常の方法AddProductは、商品をProductsコレクションに追加し、Categoryプロパティを設定するメソッドをcategoryに追加することです。

于 2010-10-13T15:22:22.930 に答える