I wrote a t-sql sp that gets a table as parameter.
I tried to call it from c#, but didn't know what type to use:
database.AddInParameter(command, "@ID", DbType.String, id);
database.AddInParameter(command, "@TemplatesIds开发者_开发问答", DbType.WhatType??, dt);
using (IDataReader reader = database.ExecuteReader(command))
{
while (reader.Read())
{
}
}
What should I use?
Since you're using a t-sql then you can use SqlDbType.Structured if you're using a SQLCommand under your (I'm guessing) IDbCommand
var dt = new DataTable();
... set up dt ...
par = new SqlParameter("@TemplatesIds", SqlDbType.Structured, dt)
There are quite a few examples of using this here on the msdn.
SqlDbType.Structured
http://msdn.microsoft.com/en-us/library/system.data.sqldbtype.aspx
maybe not the best approach, but works:
-- Create the data type
CREATE TYPE dbo.PlantList AS TABLE
(
plant_code char(1) Not Null Primary Key
)
GO
extension method
public static class DatabaseExtensions
{
public static void AddTableTypeParameter<T>(this Database database, DbCommand command, string name, string sqlType, IEnumerable<T> values)
{
var table = new DataTable();
PropertyInfo[] members = values.First().GetType().GetProperties();
foreach (var member in members)
{
table.Columns.Add(member.Name, member.PropertyType);
}
foreach (var value in values)
{
var row = table.NewRow();
row.ItemArray = members.Select(m => m.GetValue(value)).ToArray();
table.Rows.Add(row);
}
var parameter = new SqlParameter(name, SqlDbType.Structured)
{
TypeName = sqlType,
SqlValue = table
};
command.Parameters.Add(parameter);
}
}
and call as follows:
database.AddTableTypeParameter(command, "@region_filter_plants", "dbo.PlantList", regionFilterPlants.Select(p => new { plant_code = p }));
精彩评论