NHibernate绑定到DataGridView

3
为什么没有任何关于将NHibernateWinforms中的DataGridView绑定的教程呢?只有我想使用它吗? 我知道这涉及将集合绑定到DataGridView。但是我在进行CRUD时遇到了问题。
我有一个SQLite数据库+映射表:
 <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>

可运行的代码。

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

但是如果我绑定到DataGridView并使用网格来插入新行:

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);
}
< p>在session.Commit()之后,我收到了一个错误:行已被另一个事务更新或删除(或未保存值映射不正确)。在日志中,我看到NH为该新行发送UPDATE。应该是插入操作。


公共属性应该采用这种格式 => 大写字母开头。因此,FirstName而不是first_name。你懂的... 标准 - gdoron
1个回答

0

行已被另一个事务更新或删除(或未保存的值映射不正确)

这个Employee可能有一个id,因此NHibernate“认为”它应该被更新,但NHibernate找不到它,所以NH事务认为Employee在其他事务中被删除了。

id属性具有值而不是默认值。确保new_employee.id = 0;


好的,我知道发生了什么。我没有看到session.Save(new_employee)抛出异常,说我的属性为空。所以在Save之前我加了空字符串。我不知道什么是最佳实践,但我认为非空检查应该推迟到提交时进行。 - userbb
现在它可以工作了。我在提交后看到了新的记录。我只是想知道为什么NH会发送同一条记录的INSERT和UPDATE。 - userbb
@userbb。那个更新是另一个问题。阅读此处的帖子:https://dev59.com/OVPTa4cB1Zd3GeqPoPtC。希望有所帮助。 - gdoron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接