En résumé, le problème est que, lors de l'ajout d'objet enfant à la propriété collection de l'objet parent sans définir explicitement la propriété parente de l'objet enfant, le l'insertion échouera. Prenons un exemple:NHibernate 3.0 beta1 bidirectionnel un-à-plusieurs ne peut pas ajouter d'objet enfant
NOTE: J'utilise NHibernate 3.0 beta1.
Exemple: Produit Catégorie Sénario:
(1) Base de données de schéma:
- Catégorie (Id, Nom)
- produit (Id, nom, prix, CategoryId)
(2) Code C# pour les modèles de domaine
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) Mappages
<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) Appel de code
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
}
Lorsque le category.Products.Add(product)
est exécuté, le product.Category
shoule être objet category
! Si je définis explicitement la catégorie product.Category
, l'opération de validation réussira. Pourquoi cela? Le bug de NHibernate 3.0 beta1 ou autres?
NH 3.0 Beta 1 a été libéré? Il n'a pas été annoncé sur le développement nhibernate ... – codekaizen
Oui. Regardez ici: http://sourceforge.net/projects/nhibernate/files/ –