将多个 tvp 值添加到数据表时出错
Error while adding multiple tvp values to datatable
我尝试使用 table 值参数将包含多列的列表添加到 MSSQL 数据库。
我收到这个错误:
'Unable to cast object of type '...Models.OptionValue' to type
'System.IConvertible'.Couldn't store <...OptionValue> in OptionID
Column. Expected type is Int32.' InnerException:
InvalidCastException: Unable to cast object of type
'...Models.OptionValue' to type
'System.IConvertible'.
Sql Tvp table:
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 接口,但它不起作用。我该如何解决这个问题?
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);
}
我尝试使用 table 值参数将包含多列的列表添加到 MSSQL 数据库。
我收到这个错误:
'Unable to cast object of type '...Models.OptionValue' to type 'System.IConvertible'.Couldn't store <...OptionValue> in OptionID Column. Expected type is Int32.' InnerException: InvalidCastException: Unable to cast object of type '...Models.OptionValue' to type 'System.IConvertible'.
Sql Tvp table:
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 接口,但它不起作用。我该如何解决这个问题?
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);
}