将多个tvp值添加到数据表时出错

时间:2019-03-31 12:40:24

标签: c# sql datatable table-valued-parameters

我尝试使用表值参数将具有多列的列表添加到MSSQL数据库。

我收到此错误:

  

'无法转换类型为'... Models.OptionValue'的对象来键入   'System.IConvertible'。无法在OptionID中存储<... OptionValue>   柱。预期的类型为Int32。 InnerException:   InvalidCastException:无法转换类型的对象   '... Models.OptionValue'键入   “ System.IConvertible”。

Sql Tvp表:

CREATE TYPE [dbo].[OptionValueList] AS TABLE(
    [OptionID] [int] NULL,
    [ValueID] [int] NULL
)

课程:

public class OptionValue 
{
        public int OptionID { get; set; }
        public int ValueID { get; set; }
}

 public class OptionListVM
 {
        public int ProductID { get; set; }
        public List<OptionValue> OptionValueLst { get; set; }
 }

这是我尝试添加列以将列表传递到存储过程的地方:

    DataTable tvp = new DataTable();
    tvp.Columns.Add(new DataColumn("OptionID", typeof(int)));
    tvp.Columns.Add(new DataColumn("ValueID", typeof(int)));

    foreach (var x in o.OptionValueLst)               
        tvp.Rows.Add(x); -- error line

我实现了IConvertable接口,但是它不起作用。我该如何解决?

1 个答案:

答案 0 :(得分:0)

DataTable tvp = new DataTable();
tvp.Columns.Add(new DataColumn("OptionID", typeof(int)));
tvp.Columns.Add(new DataColumn("ValueID", typeof(int)));

foreach (<OptionValue>x in o.OptionValueLst) {
DataRow dr = tvp.NewRow();
dr("OptionID") = x.OptionID;
dr("ValueID") = x.ValueID; 
tvp.Rows.Add(dr); 
}