user3102419
user3102419

Reputation: 53

NHibernate Insert Into Table

How i can insert data to table with CreateQuery()?

c# class

namespace NHibernateTutorial
{
    public class Customer
    {
        public virtual int CustomerId { get; set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }           
    }
}

mapping xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                assembly="NHibernateTutorial"
                namespace="NHibernateTutorial">
  <class name="Customer">
    <cache usage="read-write"/>
    <id name="CustomerId">
      <generator class="native" />
    </id>
    <property name="FirstName" />
    <property name="LastName" />    
  </class>
</hibernate-mapping>

My program class

    var configuartion = new Configuration();
                configuartion.DataBaseIntegration(x =>
                    {
                        x.ConnectionString = @"Data Source=NH;Initial Catalog=NHibernate;Integrated Security=False;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False";
                        x.Driver<SqlClientDriver>();
                        x.Dialect<MsSql2012Dialect>();
                        x.LogFormattedSql = true;
                        x.LogSqlInConsole = true;
                        x.AutoCommentSql = true;
                    });

                configuartion.AddAssembly(Assembly.GetExecutingAssembly());

                var sessionFactory = configuartion.BuildSessionFactory();
                using (var session = sessionFactory.OpenSession())
                { 
                 var query = session.CreateQuery("INSERT INTO Customer (FirstName, LastName) select i.FirstName, i.LastName from CustomerOld i"); 
                 query.ExecuteUpdate();
                }

In this example i copy row from another table, but i need create new row, how i can do this?

Upvotes: 5

Views: 15597

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123861

The answer here is: this is not supported. Check the 13.3. DML-style operations, an extract:

The pseudo-syntax for INSERT statements is: INSERT INTO EntityName properties_list select_statement. Some points to note:

  • Only the INSERT INTO ... SELECT ... form is supported; not the INSERT INTO ... VALUES ... form.
    ...
  • select_statement can be any valid HQL select query
    ...

The idea behind DML is that you do manipulation directly on the DB side. For insertion the values must be there (somewhere).

But there is solution for your case, use the standard way:

var customer = new Customer();
customer.FirstName ...
session.Save(customer);

That's correct approach, and will do what you need

Could be interesting reading: NHibernate – Executable DML

Upvotes: 6

Related Questions