0

I'm experiencing a problem, when I try to save a instance using NHibernate on a WPF + C# application.

Debugging it, show that the errors occurs on step session.Save(MyInstance); You can see the complete method below. The error is:

An unhandled exception of type 'NHibernate.Exceptions.GenericADOException' occurred in NHibernate.dll Additional information: could not insert: [Blog.Models.Province][SQL: INSERT INTO [Province] (CodProv, NomeProv, Regiao) VALUES (?, ?, ?); select SCOPE_IDENTITY()]

private void txt_Click(object sender, RoutedEventArgs e)
{
    using(ISession session = NHibernateHelper.AbreSession())           
    {
        Province province = new Province();

            province.CodProv = "11";
            province.NomeProv = "Maputo Cidade";
            province.Regiao = "Sul";                

        ITransaction tx = session.BeginTransaction();
        session.Save(province);
        tx.Commit();
    }

The NHibernateHelper Class

public class NHibernateHelper
{
    private static ISessionFactory factory = CriaSessionFactory();

    private static ISessionFactory CriaSessionFactory()
    {
        Configuration cfg = new Configuration();
        cfg.Configure();
        ISessionFactory factory = Fluently.Configure(cfg)
           .Mappings(x =>
           {
               x.FluentMappings.AddFromAssembly(
                   Assembly.GetExecutingAssembly());
           }).BuildSessionFactory();

        return factory;
    }

    public static ISession AbreSession()
    {
        return factory.OpenSession();
    }      
}

Someone can help me?

Here's my Province and Mapping classes

public class Province
{
    public virtual int Id { get; set; }
    public virtual string CodProv { get; set; }
    public virtual string NomeProv { get; set; }
    public virtual string Regiao { get; set; }
}

Mapping class

public class ProvinceMapping : ClassMap<Province>
{
     public ProvinceMapping()
     {
          Id(province => province.Id).GeneratedBy.Identity();
          Map(province => province.CodProv);
          Map(province => province.NomeProv);
          Map(province => province.Regiao);              
     }            
}

If necessary, here's my table province script.

    CREATE TABLE Provincia(
ID INT IDENTITY(1,1) PRIMARY KEY,
codProv  VARCHAR(2) NOT NULL,
nomeProv VARCHAR(25) NOT NULL,
regiao   VARCHAR(10) );
11
  • You should show your mapping, but in this case it would be almost for sure "missing IDENTITY" on the DB colun Province_ID... And also, important: observe the rest of the exception... the next line will for sure contain the clear answer Commented Jan 19, 2015 at 8:08
  • @RadimKöhler Apparenty he is using automatic mappings. @ Elmodai, because the mapping is implicit, could you also add the code for the Province class? Commented Jan 19, 2015 at 8:27
  • @MauriceStam it is not about mapping. I would bet that the DB column "Province_ID" - table "Province" is expected to be IDENTITY... but I would say it is not. Anyhow, exactly that answer is in the exception... just next line ;) Commented Jan 19, 2015 at 8:29
  • @RadimKöhler Yes you are correct. We'll have to await the exception details. Commented Jan 19, 2015 at 8:30
  • @RadimKöhler, I just added the details (Province class) you asked. Added Mapping class to, and even the SQL Script that create the table. Commented Jan 19, 2015 at 9:45

2 Answers 2

1

Here is my config: I have 2 connectionString 1.With name Blog2 -> that I use to connect the Local DB (mdf) 2. Name Blog - > I use to connect SQL Server DB (dbo)

NHibernate only works connected to a local DB!

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <section name="hibernate-configuration"
              type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
  </configSections>

    <startup>     
      <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>

  <connectionStrings>  

    <add name="blog2" providerName="System.Data.SqlClient"
     connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Elmodai\documents\visual studio 2013\Projects\Blog\Blog\DB1.mdf;Integrated Security=True"/>

    <add name="blog" providerName="System.Data.SqlClient"
     connectionString="Data Source=ELMODAI-PC;Initial Catalog=VamosVer;Integrated Security=True"/>

  </connectionStrings>

  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="connection.provider">
        NHibernate.Connection.DriverConnectionProvider
      </property>

      <property name="dialect">
        NHibernate.Dialect.MsSql2012Dialect
      </property>

      <property name="connection.driver_class">
        NHibernate.Driver.SqlClientDriver
      </property>

      <property name="connection.connection_string_name">
        blog
      </property>

      <property name="show_sql">
        ture
      </property>

      <property name="format_sql">
        ture
      </property>

      <property name="hbm2ddl.auto">
        update
      </property>

    </session-factory>
  </hibernate-configuration>

</configuration>
Sign up to request clarification or add additional context in comments.

Comments

0

BASED ON THE MAPPING

Related to updated question, there is one inconsistence in the mapping, check the:

  • [SQL: INSERT INTO [Province] (
  • CREATE TABLE Provincia (

So, if there is no typo in the question, the problem is clear, There is no table Province... just Provincia

ORIGINAL PART

NHibernate exceptions are the real treasure, because there are all the secrets described in detail. Your exceptions, the full stack trace, most likely looks like this:

// YOUR part

An unhandled exception of type 'NHibernate.Exceptions.GenericADOException' occurred in NHibernate.dll Additional information: could not insert: [Blog.Models.Province][SQL: INSERT INTO [Province] (CodProv, NomeProv, Regiao) VALUES (?, ?, ?); select SCOPE_IDENTITY()]

// next part - inner exception

---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Province_ID', table 'Province'; column does not allow nulls. INSERT fails.

It could be even another inner exception, but from its description you will clearly now.

In case, that the issue is "column does not allow nulls" it means, that we expect:

Id(x => x.Id, "Province_ID")
   .GeneratedBy.Identity()
   ...

while DB is not set as:

[Province_ID] [int] IDENTITY(1,1) NOT NULL,

Just be sure that your ID column has the IDENTITY defined, ALTER it to have it...

3 Comments

I tried to assist ASAP... really not sure what is happening on your side... but there is last try - change your driver from SqlClientDriver to Sql2008ClientDriver.
Koler, I Just solve the problem. I need to create the table manually on SQL Server, and then, Insert data using Hibernate.
So we do have solution ;) great to see that;) Enjoy NHibernate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.