开发者

nhibernate problem on identity column

error:

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

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

Customer Class

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; }
    }
}

Actual Saving

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开发者_C百科();
session.Close();


Your code look correct. Did you create the database from the mapping file ? If it's possible do it with :

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

You can simplify your mapping file, like this :

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜