3

Why there is no any tutorial about binding NHibernate to DataGridView in Winforms. Only I want to use it? I know that this is matter of binding collection to DataGridView. But I have problems with making CRUD.

I have database SQLite+table with mapping:

 <class name="Employee" table="emplyees" lazy="true">
    <id name="id">
      <generator class="increment"></generator>
    </id>

    <property name="first_name" not-null="true"></property>
    <property name="last_name" not-null="true"></property>
    <property name="login" not-null="true"></property>
    <property name="sid"></property>         
</class>

Code that works.

Employee new_employee =
    new Employee() { first_name = "test1", last_name = "test3", login = "login1" };
session.Save(new_employee);
session.Commit();

But if I bind to DataGridView and use grid to insert a new row:

transaction = session.BeginTransaction();
employees = (from e in session.Linq<Employee>() select e).ToList<Employee>();
this.employeeBindingSource.DataSource = employees;


private void employeeDataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
Employee new_employee = (Employee)this.employeeBindingSource.Current;
session.Save(new_employee);
}

After session.Commit() I get an error: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect). In logs i see that NH sends UPDATE for that new row. Should be insert.

gdoron
  • 147,333
  • 58
  • 291
  • 367
userbb
  • 2,148
  • 5
  • 30
  • 53
  • public properties should be in this format => UpperCase. So FirstName not first_name. **standards** you know... – gdoron Feb 05 '12 at 12:12

1 Answers1

0

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

That Employee probably have an id, thus NHibernate "thinks" it should be updated, but NHibernate doesn't find it, so NH transaction thinks the Employee was deleted in some other transaction.

That id property has a value and not the default value. make sure new_employee.id = 0;

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • Ok. I know what happened. I don't saw exception thrown by session.Save(new_employee); saying that my properties are null. So I put empty string before Save. I don't know what is best practice but I think not-null checking should be deferred to commit. – userbb Feb 05 '12 at 12:29
  • And now it works. I see new record after commit. I only wonder why NH sends INSERT and after it UPDATE of same record. – userbb Feb 05 '12 at 12:30
  • @userbb. That update is an other issue. read [this](http://stackoverflow.com/questions/4883900/what-does-inverse-and-cascade-means-in-nhibernate) post here. hope it helped. – gdoron Feb 05 '12 at 13:07