[英]Adding Trigger to Oracle DB using NHibernate
I'm trying to write small program that will generate my DB tables, sequences and trigger from code, using NHibernate. 我正在尝试编写一个小程序,该程序将使用NHibernate从代码生成数据库表,序列和触发器。
With SchemaExport.Create()
method I was able to create all the table and relevant sequences, but I was not able to create triggers. 使用
SchemaExport.Create()
方法,我可以创建所有表和相关序列,但无法创建触发器。 Therefore I tried to use session.CreateSQLQuery()
to run command that adds the trigger to the DB. 因此,我尝试使用
session.CreateSQLQuery()
运行将触发器添加到数据库的命令。
My code looks like this: 我的代码如下所示:
string createTriggerQuery= @"create or replace trigger table_insert_trigger before insert on Table for each row begin select TableSequence.nextval into :new.ID from dual; end;";
var query = session.CreateSQLQuery(createTriggerQuery);
query.ExecuteUpdate();
The query works as I run it on the Oracle SQL Developer
, but as I execute my code I'm getting this exception: 该查询在我在
Oracle SQL Developer
上运行时起作用,但是在执行代码时却遇到此异常:
Could not execute native bulk manipulation query:create or replace trigger... [SQL: SQL not available]
I also tried to use HBM queries to create the query. 我也尝试使用HBM查询来创建查询。 I add XML file to the project as embedded resource and on it I add the following code:
我将XML文件作为嵌入式资源添加到项目中,并在其上添加以下代码:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<database-object>
<create>
create or replace
trigger table_insert_trigger before insert on table
for each row
when (new.ID is NULL)
begin
select tableSequence.nextval into :new.ID from dual;
end;
</create>
and in my FluentConfiguration
member I configured it to add hbm mapping: 在我的
FluentConfiguration
成员中,我将其配置为添加hbm映射:
_fluentConfiguration.Mappings(m => m.HbmMappings.AddFromAssemblyOf<DbContextFactory>());
but that was not working either. 但这也不起作用。
Does anyone know how can I add the trigger to my DB from code? 有谁知道如何从代码将触发器添加到数据库中?
The problem in this particular instance is the query you are trying to execute against the database, specifically this part: 在此特定实例中的问题是您要针对数据库执行的查询,特别是以下部分:
... into :new.ID from dual;
The colon ( :
) is being interpreted by NHibernate as an indicator of a parameter, and substituting it with ?
冒号(
:
)正在由NHibernate的解释为参数的指示符,并用它取代?
(since you aren't actually passing a parameter). (因为您实际上没有传递参数)。 So it is actually passing an SQL that looks like this,
因此它实际上正在传递一个看起来像这样的SQL,
into ? from dual
At which point Oracle complains. 在这一点上甲骨文抱怨。
Currently, there is no way for NHibernate to escape the :
and pass it literally to the database, as noted here . 目前,还没有办法NHibernate的逃离
:
从字面上把它传递到数据库,注意这里 。
Under a similar constraint, the solution was to use an ORM
other than NHibernate. 在类似的约束下,解决方案是使用NHibernate以外的
ORM
。 If this is the required purpose, maybe NHibernate is not the best option. 如果这是必需的目的,则NHibernate可能不是最佳选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.