Skip to main content
 首页 » 编程设计

c#之在 NHibernate 中使用命名参数作为表名

2024年02月05日11yyy_WW

我需要对名为 myTable 的表执行简单的截断。所以我写了这个并且它有效:

statelessSession 
    .CreateSQLQuery("TRUNCATE TABLE myTable") 
    .ExecuteUpdate(); 

因为我会将表名存储在 App.config 中,所以我会将查询“参数化”。我会避免 String.Format 所以我尝试了类似的东西

statelessSession 
    .CreateSQLQuery("TRUNCATE TABLE :tabName") 
    .SetParameter("tabName", SysCfg.ConfigurationManager.AppSettings["tabName"]) 
    .ExecuteUpdate(); 

但是当我运行这段代码时,我得到:

Additional information: could not execute native bulk manipulation query: 
   TRUNCATE TABLE :seedTableName[SQL: TRUNCATE TABLE @p0] 

我也试过在参数名称周围使用花括号,但这也不起作用。

我哪里错了?

请您参考如下方法:

表格作为参数在这里解释

Table name as variable

Table names and column names need to be static, if the query is static. For dynamic table or column names, you should generate the full SQL dynamically,

因此,您应该将其构建为纯字符串

statelessSession 
    .CreateSQLQuery("TRUNCATE TABLE " + SysCfg.ConfigurationManager.AppSettings["tabName"]) 
    .ExecuteUpdate();