【发布时间】: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.Object 或 NHibernateUtil.Class),NHibernate 抱怨:
NHibernate.HibernateException:无法确定类的类型:<>f__AnonymousType5`2[[System.Int32],[System.String]]
如果我尝试使用 movieID 和 score 的属性创建 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