NHibernate.PropertyValueException:not-null属性引用null或transient

时间:2010-06-02 17:50:41

标签: nhibernate nhibernate-mapping

我收到以下异常。

NHibernate.PropertyValueException:not-null属性引用null或transient

这是我的映射文件。

产品

  <class name="Product" table="Products">
    <id name="Id" type="Int32" column="Id" unsaved-value="0">
      <generator class="identity"/>
    </id> 
    <set name="PriceBreaks" table="PriceBreaks" generic="true" cascade="all" inverse="true" >
      <key column="ProductId" />
      <one-to-many class="EStore.Domain.Model.PriceBreak, EStore.Domain" />
    </set>    

  </class>

价格突破

 <class name="PriceBreak" table="PriceBreaks">
    <id name="Id" type="Int32" column="Id" unsaved-value="0">
      <generator class="identity"/>
    </id>
    <property name="ProductId" column="ProductId" type="Int32" not-null="true" />

    <many-to-one name="Product" column="ProductId" not-null="true" cascade="all" class="EStore.Domain.Model.Product, EStore.Domain" />  

  </class>

我在以下方法上获得了例外

[Test]
public void Can_Add_Price_Break()
{

    IPriceBreakRepository repo = new PriceBreakRepository();

    var priceBreak = new PriceBreak();

    priceBreak.ProductId = 19;
    repo.Add(priceBreak);

    Assert.Greater(priceBreak.Id, 0);
}

跟进Jan回复。我从priceBreak地图中删除了ProductId。这有效!!

    public int AddPriceBreak(Product product, PriceBreak priceBreak)
    {


        using (ISession session = EStore.Domain.Helpers.NHibernateHelper.OpenSession())
        using (ITransaction transaction = session.BeginTransaction())
        {

            product.AddPriceBreak(priceBreak);
            session.SaveOrUpdate(product);
            transaction.Commit();
        }

        return priceBreak.Id;
    }

2 个答案:

答案 0 :(得分:2)

从映射和PriceBreak类中删除ProductId属性。并使用PriceBreaks集合添加PriceBreaks,您不需要PriceBreakRepository,只需要ProductRepository。

示例:

using (var session = sessionFactory.OpenSession()) 
{
  using (var tx = session.BeginTransaction()) 
  {

    var product = session.Get<Product>(19);
    product.AddPriceBreak(new PriceBreak());

    tx.Commit();
   }
 }

在产品中:

class Product 
{
   // ...
   public void AddPriceBreak(PriceBreak pb) 
   {
     pb.Product = this;
     PriceBreaks.Add(pb);
   }
 }

答案 1 :(得分:1)

您对Id属性的使用以及实际引用不正确。

首先,删除此行:

<property name="ProductId" column="ProductId" type="Int32" not-null="true" />

然后,不要分配ProductId(您应该完全删除该属性),请使用:

priceBreak.Product = session.Load<Product>(19);

(您可能需要将Load方法添加到存储库中。)

相关问题