单位列上的nhibernate问题

单位列上的nhibernate问题,nhibernate,mapping,Nhibernate,Mapping,错误: 无法插入:[NHibernateeExperiment.Domain.Customer][SQL:插入到客户(名字、姓氏、地址)值(?,?);选择范围\标识() 映射: <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="NHibernateExperiment.D

错误:


无法插入:[NHibernateeExperiment.Domain.Customer][SQL:插入到客户(名字、姓氏、地址)值(?,?);选择范围\标识()

映射:

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

  <class name="Customer" table="Customer">
    <id name="CustomerID"  type="int" unsaved-value="0">
      <generator class="native" />
    </id>
    <property name="FirstName" type="String" length="50"/>
    <property name="LastName" type="String" length="50"/>
    <property name="Address"   type="String" length="100"/>

  </class>
</hibernate-mapping>
实际节省

Configuration cfg = new Configuration();
ISessionFactory factory = cfg.Configure(Server.MapPath("hibernate.cfg.xml")).BuildSessionFactory();
ISession session = factory.OpenSession();
ITransaction transaction = session.BeginTransaction();

Customer customer = new Customer();
customer.FirstName = "Firstname";
customer.LastName = "lastname";            
customer.Address = "Address";

// Tell NHibernate that this object should be saved
session.Save(customer);

// commit all of the changes to the DB and close the ISession
transaction.Commit();
session.Close();

您的代码看起来是正确的。您是否从映射文件创建了数据库?如果可能的话,可以使用:

public void CreateDatabaseSchemaFromMappingFiles()
{
    NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
    cfg.Configure();
    SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
    NHibernate.Tool.hbm2ddl.SchemaExport schema = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
    schema.Create(false, true);
}
您可以简化映射文件,如下所示:

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

  <class name="Customer" table="Customer">
    <id name="CustomerID"  type="int">
      <generator class="native" />
    </id>
    <property name="FirstName" length="50"/>
    <property name="LastName" length="50"/>
    <property name="Address" length="100"/>
  </class>
</hibernate-mapping>

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

  <class name="Customer" table="Customer">
    <id name="CustomerID"  type="int">
      <generator class="native" />
    </id>
    <property name="FirstName" length="50"/>
    <property name="LastName" length="50"/>
    <property name="Address" length="100"/>
  </class>
</hibernate-mapping>