NHibernate插入表

时间:2013-12-14 15:42:08

标签: c# nhibernate

如何使用CreateQuery()将数据插入表?

c#c​​lass

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

映射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>

我的课程班级

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

在这个例子中我从另一个表复制行,但我需要创建新行,我该怎么做?

1 个答案:

答案 0 :(得分:6)

这里的答案是:不支持此功能。查看13.3. DML-style operations,摘录:

  

INSERT语句的伪语法是:INSERT INTO EntityName   properties_list select_statement。有些要点需要注意:

     
      
  • 仅支持INSERT INTO ... SELECT ...表单; 不是INSERT INTO ... VALUES ...表格
      ...
  •   
  • select_statement可以是任何有效的HQL选择查询
      ...
  •   

DML背后的想法是你直接在数据库端进行操作。对于插入,值必须在某处(某处)。

但是 您的案例的解决方案,请使用标准方式:

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

这是正确的方法,并将做你需要的

可能有趣的阅读:NHibernate – Executable DML