NHibernate.PropertyValueException: свойство not-null ссылается на null или переходный процесс - PullRequest
2 голосов
/ 02 июня 2010

Я получаю следующее исключение.

NHibernate.PropertyValueException: свойство not-null ссылается на нулевое или временное значение

Вот мои файлы сопоставления.

Продукт

  <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);
}

Вслед за январским ответом. Я удалил ProductId из карты priceBreak. Это работает !!

    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 ]

2 голосов
/ 02 июня 2010

Удалите свойство ProductId из сопоставления и из класса PriceBreak. И используйте коллекцию PriceBreaks для добавления PriceBreaks, вам не нужен репозиторий PriceBreak, а только репозиторий Product.

Пример:

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 голос
/ 02 июня 2010

Неверное использование вами свойств Id вместе с реальными ссылками.

Сначала удалите эту строку:

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

Затем, вместо присвоения ProductId (вам следует полностью удалить это свойство), используйте:

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

(вам может понадобиться добавить метод Load в ваш репозиторий).

...