执行添加功能
private void buttonAdd_Click(object sender, EventArgs e)
{
Customer customer = new Customer();
customer.CustomerId =Int32.Parse(this.textBoxCustomerId.Text);
customer.FirstName = this.textBoxFirstName.Text;
customer.LastName = this.textBoxLastName.Text;
customer.Version =Int32.Parse( this.textBoxVersion.Text);
reference.Add(customer);
comboBox.Items.Add(this.textBoxCustomerId.Text);
}
时出现could not insert: [fuck.Model.Customer][SQL: INSERT INTO Customer (FirstName, LastName, Version) VALUES (?, ?, ?); select SCOPE_IDENTITY()]
"不能将值 NULL 插入列 'CustomerId',表 'NHibernateSample.dbo.Customer';列不允许有空值。INSERT 失败。\r\n语句已终止。"}
持久类是public class Customer
{
public virtual int CustomerId { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual int Version { get; set; }
public virtual ISet<Order> Order { get; set; }
}
映射文件是
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="fuck.Model.Customer,fuck.Model" table="Customer">
<id name="CustomerId" type="Int32" unsaved-value="null">
<column name="CustomerId" length="4" sql-type="int" not-null="true" unique="true" index="PK_Customer"/>
<generator class="native" />
</id>
<property name="FirstName" type="String">
<column name="FirstName" length="50" sql-type="varchar" not-null="true"/>
</property>
<property name="LastName" type="String">
<column name="LastName" length="50" sql-type="varchar" not-null="true"/>
</property>
<property name="Version" type="int">
<column name="Version" length="4" sql-type="int" not-null="true"/>
</property>
<!--一对多关系:Customer有一个或多个Orders-->
<set name="Order" table="Order" generic="true" inverse="true">
<key column="CustomerId" foreign-key="FK_Order_Customer"/>
<one-to-many class="fuck.Model.Order,fuck.Model"/>
</set>
</class>
</hibernate-mapping>
CustomerId 应该是你的主键吧,就算不是那你肯定是设置为不能为空同时没有设置默认值
你在插入的时候CustomerId 没有插入数据,数据库又要求不能为null,就出现这个错了
主键的话CustomerId 设成自增的啊
主键要设置默认值的吗?我也是懵逼了
数据库里的CustomerId有没有设自增?
我也遇到这个问题,我这边的情况是因为表中有外键,外键的值在另外一个表中对应是空的。把外键所在的表也加上数据就可以了。