Pass (Data Table) to SQL Server From ASP.NET using Enterprise Library

倾然丶 夕夏残阳落幕 提交于 2019-12-03 20:10:50

I have to modify @eduardo's code to make me work in my case with Enterprise Library:

    public int Insert(int id, DTO mnemonics)
    {
        DatabaseProviderFactory factory = new DatabaseProviderFactory();
        Database Db = factory.CreateDefault();

        using (var dbCommand = Db.GetStoredProcCommand("spINSERT"))
        {
            using (var table = new DataTable())
            {
                table.Columns.Add("Key", typeof(string));
                table.Columns.Add("Value", typeof(string));
                foreach (KeyValuePair<string, string> item in mnemonics.data)
                {
                     var row = table.NewRow();
                     row["Key"] = item.Key;
                     row["Value"] = item.Value;
                     table.Rows.Add(row);
                }

                Db.AddInParameter(dbCommand, "id", DbType.int, id);
                SqlParameter p = new SqlParameter("MNEMONICS", table);
                p.SqlDbType = SqlDbType.Structured;
                dbCommand.Parameters.Add(p);

                Db.ExecuteNonQuery(dbCommand);
            }
        }
    }

My type in SQL Server:

CREATE TYPE [dbo].[StringDict] AS TABLE(
    [Key] [varchar](max) NULL,
    [Value] [varchar](max) NULL
)

I hope help someone

"DbType.Structured" Table valued parameters are not supported in the enterprise library . If you want to use a table as a parameter to a stored proc or query, you'll have to use the underlying store connection and the support that is provided there.

Eduardo

DbType.Structured Table valued parameters are not supported in the enterprise library, but it is posible to used this way:

db = DatabaseFactory.CreateDatabase();
using (DbCommand cmd = db.GetStoredProcCommand("Sp_Candidate"))
{
    db.AddInParameter(cmd, "@candidateid", DbType.Int32, txtCandidateID.text);
    cmd.Parameters.Add(new SqlParameter("candidateSkillSets", candidateSkillSets) { SqlDbType = SqlDbType.Structured });
    db.ExecuteNonQuery(cmd);
}

How to pass an array into a SQL Server stored procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!