在集合中找不到参数'param_name'

时间:2014-03-12 00:03:46

标签: c# mysql asp.net parameters

这是我第一次尝试使用ADO.NET for MySQL,我不知道发生了什么。我一直在尝试定义的第一个参数上收到错误Parameter '_name' not found in collection

我尝试过重新排序,但无论我采用哪种方式,MySQL总是赶上第一行。

mySqlCommand = mySqlConnect.CreateCommand();
mySqlCommand.CommandText = "SELECT MajorEquipment.EquipmentNumber, MajorEquipment.EquipmentType, PlantAreaCodes.AreaCode " +
  "FROM MajorEquipment e INNER JOIN PlantAreaCodes a " +
  "ON e.PACId = a.PACId WHERE " +
  "(@EquipmentType IS NULL OR e.EquipmentType = @EquipmentType) " +
  "AND (@EquipmentNumber IS NULL OR e.EquipmentNumber = @EquipmentNumber) " +
  "AND (@AreaCode IS NULL OR a.AreaCode = @AreaCode)";

// The First line shows the error. I have tried @EquipmentType, 
// @EquipmentNumber, and @AreaCode in the first line.

mySqlCommand.Parameters["@EquipmentType"].Value = (string.IsNullOrEmpty(MeModel.EquipmentType) ? (object)DBNull.Value : MeModel.EquipmentType);
mySqlCommand.Parameters["@EquipmentNumber"].Value = (string.IsNullOrEmpty(MeModel.EquipmentNumber) ? (object)DBNull.Value : MeModel.EquipmentNumber);
mySqlCommand.Parameters["@AreaCode"].Value = (string.IsNullOrEmpty(MeModel.Location) ? (object)DBNull.Value : MeModel.Location);

mySqlReader = mySqlCommand.ExecuteReader();

第一个参数显示错误,但我开始相信它可能与命令字符串有关。

我还尝试分别用ea替换MajorEquipmentAreaCode

为什么会这样?

以下是我的参考表:

+----------------+    +-----------------+
| PlantAreaCodes |    | MajorEquipment  |
|----------------|    |-----------------|
| PACId (PKEY)   |    | MEId (PKEY)     |
| AreaCode       |    | EquipmentType   |
| AreaName       |    | PACId (FKEY)    |
| Comments       |    | EquipmentNumber |
+----------------+    +-----------------+

1 个答案:

答案 0 :(得分:2)

您需要在设置值之前将参数添加到集合中或使用快捷方式 AddWithValue

mySqlCommand.Parameters.AddWithValue("@EquipmentType", (string.IsNullOrEmpty(MeModel.EquipmentType) ? (object)DBNull.Value : MeModel.EquipmentType));
mySqlCommand.Parameters.AddWithValue("@EquipmentNumber", (string.IsNullOrEmpty(MeModel.EquipmentNumber) ? (object)DBNull.Value : MeModel.EquipmentNumber));
mySqlCommand.Parameters.AddWithValue("@AreaCode", (string.IsNullOrEmpty(MeModel.Location) ? (object)DBNull.Value : MeModel.Location));