使用DatabaseFactory通过传递TableType来调用存储过程

时间:2015-06-02 14:15:10

标签: sql-server-2008 c#-4.0 ado.net

我在尝试将表类型传递给存储过程时遇到错误

使用数据类型名称

创建数据表dataTableMyData
DataTable dataTableMyData = new DataTable("myTableType");

我的代码:

 DatabaseFactory.ClearDatabaseProviderFactory();
 DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
 Database db = DatabaseFactory.CreateDatabase();
 DataSet dsResult = new DataSet();
  DbCommand cmd = db.GetStoredProcCommand("sp_Save_Clue_Auto_Response"))
  db.AddInParameter(cmd, "@myTableType", System.Data.SqlDbType.Structured, dataTableMyData);

如何使用DatabaseFactory传递表类型。请帮帮我。

2 个答案:

答案 0 :(得分:1)

您的代码没有执行命令?您是否忘记在样本中发布该内容?

DataTable table = new DataTable();
SqlDatabase database = (SqlDatabase) DatabaseFactory.CreateDatabase("DatabaseName");
DbCommand dbCommand = database.GetStoredProcCommand("[StoredProcName]");
database.AddInParameter(dbCommand, "@MyTvp",SqlDbType.Structured, table);
DataSet dataSet = database.ExecuteDataSet(dbCommand);

答案 1 :(得分:0)

可能不是最好的方法,但有效:

-- Create the data type
CREATE TYPE dbo.PlantList AS TABLE 
(
    plant_code char(1) Not Null Primary Key
)
GO

扩展方法

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);
    }

}

并致电如下:

database.AddTableTypeParameter(command, "@region_filter_plants", "dbo.PlantList", regionFilterPlants.Select(p => new { plant_code = p }));