使用ServiceStack ORMLite将DataTable传递给SP

时间:2013-11-13 12:02:46

标签: c# servicestack ormlite-servicestack

我必须调用一个存储过程,但是传递一个数据表(一个iEnumerable)作为参数。

SQL服务器上的我的SP将此参数视为:

@LIST_USERS dbo.LIST_USERINFO_TYPE READONLY

,类型定义为:

CREATE TYPE [dbo].[LIST_USERINFO_TYPE] AS TABLE(
   [ID_USER] [int] NOT NULL,
   [ID_DATA] [int] NOT NULL,
   [HEADER_TXT] [varchar](100) NULL)

然后,在调用者方面,我以这种方式创建参数:

list.Add(new UserInfoItem { IdUser = 401, IdData = 3, HeaderTxt = "" });
list.Add(new UserInfoItem { IdUser= 402, IdData= 2, HeaderTxt= "gotcha" });
list.Add(new UserInfoItem { IdUser= 403, IdData= 1, HeaderTxt= "pacific rim" });

dbConn.StoredProcedure(sp,
  new
    {
      LISTA_QUESTIONARIO = DomandeRisposteList
    });

当我启动项目时,实际上它会在KeyNotFoundException尝试

时停止
name.DbType = OrmLiteConfig.DialectProvider.GetColumnDbType(propertyInfo.PropertyType);
ServiceStackExtension.cs

中的

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:7)

我已经使用简单的数据表找到了答案:

        DataTable dataTableTmp = new DataTable();
        dataTableTmp.Columns.Add("ID_USER", typeof(Int32));
        dataTableTmp.Columns.Add("ID_DATA", typeof(Int32));
        dataTableTmp.Columns.Add("HEADER_TXT", typeof(string));


        foreach (var r in DomandeRisposteList)
        {
            DataRow ro = dataTableTmp.NewRow();
            ro[0] = r.IdUser;
            ro[1] = r.IdData ;
            ro[2] = r.HeaderTxt ;

            dataTableTmp.Rows.Add(ro);
        }

        var dbConn = dbFactory.OpenDbConnection();

        var res = dbConn.Exec(dbCmd =>
        {
            dbCmd.CommandType = CommandType.StoredProcedure;
            dbCmd.Parameters.Add(new SqlParameter("@LISTA_QUESTIONARIO", dataTableTmp));
            dbCmd.CommandText = "IF_SP_QUESTIONARIO_INSERT_TEST";
            return dbCmd.ExecuteReader().ConvertToList<DomandeRisposteItem>(); 
        });

        return res;

答案 1 :(得分:2)

在Pizzaboys上构建答案...看起来你不能在ExecuteReader()之后使用ConvertToList和更新版本的servicestack

我必须这样做:

var res = dbConn.Exec(dbCmd =>
{
    dbCmd.CommandType = CommandType.StoredProcedure;
    dbCmd.Parameters.Add(new SqlParameter("@LISTA_QUESTIONARIO", dataTableTmp));
    dbCmd.CommandText = "IF_SP_QUESTIONARIO_INSERT_TEST";
    rtnList = dbCmd.ConvertToList<DomandeRisposteItem>(); 
});

答案 2 :(得分:1)

基于PizzaBoy的回答,首先创建一个DataTable并填充。出于我的目的(没有返回的记录),以下内容适用于ServiceStack的v4。

        //var Db = DbFactory.OpenDbConnection(); // I already have Db as IDbConnection from 'RepositoryBase'
        using (var dbCmd = Db.OpenCommand())
        {
            dbCmd.CommandType = CommandType.StoredProcedure;
            dbCmd.CommandText = "dbo.StoredProcName";
            dbCmd.Parameters.Add(new SqlParameter("@tvpName", dataTableTmp));
            dbCmd.ExecuteNonQuery();
        }