views:

28

answers:

2

Please, help! I new to nHibernate and I stuck on problem - I can't create new persisted object via NHibernate (2)

In this code:

foreach (var item in items)
{
 if (item.price > 0)
 {
  if (_itemsForBuy.FirstOrDefault(i => item.itemid == i.itemId) == null)
  {
   var ifb = new ItemForBuy()
   {
    id = 0,
    item = item,
    count = 100
   };

   ISession session = SessionHelper.CurrentSession;
   ifb.id = (int)session.Save(ifb); //at first iteration returs 0, at second - exception
   _itemsForBuy.Add(ifb);
  }
 }
}

...on second iteration thrown exception:

could not insert: [xxx.ItemForBuy][SQL: INSERT INTO itemsforbuy (count, itemid) VALUES (?, ?)]

with inner exception:

Duplicate entry '0' for key 'PRIMARY'

ItemForBuy.hbm.xml:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="xxx"
                   namespace="xxx">

  <class name="ItemForBuy" table="itemsforbuy" lazy ="false">

    <id name="id" type="Int32" column="id" unsaved-value="0">
      <generator class="identity"/>
    </id>
...

class:

public class ItemForBuy
{
 public int id
 {
  get;
  set;
 }
...

in db:

CREATE  TABLE IF NOT EXISTS `xxx`.`itemsforbuy` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `itemid` INT NOT NULL ,
  `count` INT NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB

What I doing wrong?

A: 

Try this generator:

<id name="Id" column="Id" type="int">
    <generator class="native"></generator>
</id>

NHibernate and MySql - a simple example on how to use it

Rafael Belliard
same problem(( any way, thanks for the link
Win4ster
A: 

Problem solved. The reason was in not AUTO_INCREMENT 'id' field. I didn't synchronize MySQL Workbench with DB, and I thought that id is auto increment, but it wasn't true.

Win4ster