Pizzaboy Pizzaboy - 3 months ago 20
C# Question

Passing a DataTable to a SP with ServiceStack ORMLite

I have to call a Stored Procedure but passing a datatable (an iEnumerable) as parameter.

My SP on the SQL server takes this parameter as:

@LIST_USERS dbo.LIST_USERINFO_TYPE READONLY


and the type is defined as:

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


Then, on the caller side i create the parameters in this way:

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


When i launch the project actually it stops with a
KeyNotFoundException
trying to

name.DbType = OrmLiteConfig.DialectProvider.GetColumnDbType(propertyInfo.PropertyType);


in
ServiceStackExtension.cs


How can I achieve this?

Answer

I've found the answer on my own using simple Datatables:

        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;