【问题标题】:How can I get NHibernate to make a multicolumn table-valued parameter?如何让 NHibernate 创建一个多列表值参数?
【发布时间】:2017-09-15 17:10:14
【问题描述】:

我想将一个两列的表值参数 (TVP) 传递给 ISQLQuery

var sql = "INSERT INTO MovieRatings (PersonID, MovieID, Score) " +
          "SELECT :personID, o.movieID, o.score " +
          "FROM :scoreObject o";
var query = session.CreateSQLQuery(sql);
query.SetInt32("personID", fred.ID);
query.SetParameterList("scoreObject", fredsRatings.Select(r => new {
        movieID = r.Movie.ID,
        score = r.Score
    }).ToArray() /*, Optional IType hint here */);
query.ExecuteUpdate();

当我这样做时(或尝试将 IType 提示为 NHibernateUtil.ObjectNHibernateUtil.Class),NHibernate 抱怨:

NHibernate.HibernateException:无法确定类的类型:<>f__AnonymousType5`2[[System.Int32],[System.String]]

如果我尝试使用 movieIDscore 的属性创建 struct 并创建一个由这些属性组成的数组而不是匿名对象,它也会抱怨。唯一改变的是它“无法确定”的类型。

Microsoft seems to say TVP 可以包含您想要的任何列:

将表值参数传递给参数化 SQL 语句

以下示例演示如何使用带有SELECT 子查询的INSERT 语句将数据插入到dbo.Categories 表中,该子查询具有表值参数作为数据源。将表值参数传递给参数化 SQL 语句时,必须使用 SqlParameter 的新 TypeName 属性为表值参数指定类型名称。此TypeName 必须与先前在服务器上创建的兼容类型的名称匹配。此示例中的代码使用TypeName 属性来引用dbo.CategoryTableType 中定义的类型结构。

// Assumes connection is an open SqlConnection.  
using (connection)  
{  
    // Create a DataTable with the modified rows.  
    DataTable addedCategories = CategoriesDataTable.GetChanges(  
        DataRowState.Added);  

    // Define the INSERT-SELECT statement.  
    string sqlInsert =   
        "INSERT INTO dbo.Categories (CategoryID, CategoryName)"  
        + " SELECT nc.CategoryID, nc.CategoryName"  
        + " FROM @tvpNewCategories AS nc;"  

    // Configure the command and parameter.  
    SqlCommand insertCommand = new SqlCommand(  
        sqlInsert, connection);  
    SqlParameter tvpParam = insertCommand.Parameters.AddWithValue(  
        "@tvpNewCategories", addedCategories);  
    tvpParam.SqlDbType = SqlDbType.Structured;  
    tvpParam.TypeName = "dbo.CategoryTableType";  

    // Execute the command.  
    insertCommand.ExecuteNonQuery();  
}

有没有办法说服 NHibernate 制作带有命名列的 TVP?我想避免writing my own IType.

【问题讨论】:

    标签: nhibernate table-valued-parameters


    【解决方案1】:

    Remondo 有a novel solution 解决此问题:使用 Microsoft 库中的 SqlParameter 将 TVP 定义添加到事务中。

    编辑以跟随问题中查询的示例代码。

    【讨论】:

      猜你喜欢
      • 2017-03-30
      • 2011-05-14
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 2019-08-24
      • 2011-09-21
      • 1970-01-01
      • 2021-05-27
      相关资源
      最近更新 更多