我正在尝试使用ado.net连接将字典中存在的详细信息存储到SQL Server中,但是当我尝试向数据库中插入值时出现未找到键的异常。
if(option==2)
{
SqlConnection con = new SqlConnection("Data Source=.;Database=Demo;Integrated Security=SSPI");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO tnlFourWheeler(Vno, years, cost,color,fuel,doors,seats) " +
" VALUES (@Vno, @years, @cost,@color,@fuel,@doors,@seats)", con);
for (int i = 0; i < keyValuePairs.Count; i++)
{
FourWheeler t = (FourWheeler)keyValuePairs[i];
cmd.Parameters.AddWithValue("@Vno", t.vehicleNumber);
cmd.Parameters.AddWithValue("@years", t.numberOfYears);
cmd.Parameters.AddWithValue("@cost", t.cost);
cmd.Parameters.AddWithValue("@color", t.color);
cmd.Parameters.AddWithValue("@fuel", t.fuelType);
cmd.Parameters.AddWithValue("@doors", t.doors);
cmd.Parameters.AddWithValue("@seats", t.seats);
cmd.ExecuteNonQuery();
}
con.Close();
答案 0 :(得分:0)
Dictionary<TKey,TValue>
未通过array-index进行索引,而是通过键进行了索引。
执行此操作(将TKey
替换为实际的TKey
):
foreach( KeyValuePair<TKey,FourWheeler> kvp in keyValuePairs )
{
FourWheeler t = kvp.Value;
// ...
}
或者:
foreach( TKey key in keyValuePairs.Keys )
{
FourWheeler t = keyValuePairs[key];
// ...
}