身份栏上的nhibernate问题

时间:2009-11-14 06:10:41

标签: nhibernate mapping

错误:

could not insert: [NHibernateExperiment.Domain.Customer][SQL: INSERT INTO Customer (FirstName, LastName, Address) VALUES (?, ?, ?); select SCOPE_IDENTITY()]

映射:

<?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>

客户类

namespace NHibernateExperiment.Domain
{
    public class Customer
    {
        public virtual int CustomerID { get; set; }
        public virtual String FirstName { get; set; }
        public virtual String LastName { get; set; }
        public virtual String Address { get; set; }
    }
}

实际保存

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();

1 个答案:

答案 0 :(得分:0)

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

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>