Ankush Band
Ankush Band

Reputation: 6

Can we avoid auto increment for primary key ID column using NHibernate in .hbm.xml mapping file

Following is my database script of mssql I create table Department in this dept is primary key but not auto incremented and there datatype is varchar.

create table Department(
    deptid varchar(30) NOT NULL CONSTRAINT deptid_P_KEY PRIMARY KEY,
    departmentname varchar(100)
    )

Following is my Mapping file.

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping assembly="TestDal" namespace="NHSample.TestDal.Dal" xmlns="urn:nhibernate-mapping-2.2">
  <class name="DepartmentEntity" table="Department" lazy="true" >
    <id name="DeptId" >
      <generator class="assigned" />
      <column name="deptid" sql-type="varchar" not-null="true" />
    </id>
    <property name="Departmentname">
      <column name="departmentname" sql-type="varchar" not-null="false" />
    </property>
  </class>
  </hibernate-mapping>

When I run and at time of configure connection string path then it gives error -

XML validation error: The 'type' attribute is not declared.

Following is my configuration code:

   static Configuration nhConfiguration;
static ISessionFactory nhSessionFactory;
internal static void CreateSessionFactory(string configFilePath)
{  
    nhConfiguration = new Configuration();
    try
    {
        if (string.IsNullOrEmpty(configFilePath))
            nhConfiguration.Configure();
        else
            nhConfiguration.Configure(configFilePath);

        nhConfiguration.SessionFactory().DefaultFlushMode(flushMode);
    }
    catch (Exception exception)
    {
        throw new NHException("Failed to configure session factory.", exception);
    }
    try
    {
        nhSessionFactory = nhConfiguration.BuildSessionFactory();
    }   
}

in above code following line gives error: nhConfiguration.Configure(configFilePath);

so how to do this using nhibernate.

Upvotes: 0

Views: 638

Answers (1)

David Osborne
David Osborne

Reputation: 6791

I think you might need to change your id mapping to:

<id name="DeptId" generator="assigned" column="deptid" type="string"/>

The type attribute is optional and can be omitted if the underlying property is the same type.

Upvotes: 1

Related Questions