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?