在我的MVC应用程序中有一个方法
public void insertAddress(AddressModel address)
{
var connection = OpenConnection();
var command = connection.CreateCommand();
command.CommandText = "insert into Adres (AddressLine_1,AddressLine_2,Postcode,Town,DateMovedIn,Id) values (@AddressLine_1, @AddressLine_2, @Postcode, @Town,@DateMovedIn,@Id)";
AddParameterString(command, "@AddressLine_1", address.AddressLine_1);
AddParameterString(command, "@AddressLine_2", address.AddressLine_2);
AddParameterString(command, "@Postcode", address.Postcode);
AddParameterString(command, "@Town", address.Town);
AddParameterString(command, "@DateMovedIn", address.DateMovedIn.ToString("yyyyMMdd"));
AddParameterInt(command, "@Id", address.Id);
command.ExecuteNonQuery();
}
模型中的 AddressLine2
不是必需的。当用户未提交AddressLine2
时,我收到错误消息:
参数化查询'(@ AddressLine_1 nvarchar(3),@ AddressLine_2 为nvarchar(4000),@ POSTC'期望参数' @ AddressLine_2',哪个 没有提供。
如何在两种情况下修改此方法 - 用户提交AddressLine2
而用户未提交AddressLine2
?
答案 0 :(得分:2)
public void insertAddress(AddressModel address)
{
var connection = OpenConnection();
var command = connection.CreateCommand();
command.CommandText = "insert into Adres (AddressLine_1,AddressLine_2,Postcode,Town,DateMovedIn,Id) values (@AddressLine_1, @AddressLine_2, @Postcode, @Town,@DateMovedIn,@Id)";
command.Parameters.Add(new SqlParameter { ParameterName = "@AddressLine_1", Value = address.AddressLine_1 });
if (address.AddressLine_2 == null)
{
command.Parameters.Add(new SqlParameter { ParameterName = "@AddressLine_2", Value = DBNull.Value });
}
else
{
command.Parameters.Add(new SqlParameter { ParameterName = "@AddressLine_2", Value = address.AddressLine_2 });
}
command.Parameters.Add(new SqlParameter { ParameterName = "@Postcode", Value = address.Postcode });
command.Parameters.Add(new SqlParameter { ParameterName = "@Town", Value = address.Town });
command.Parameters.Add(new SqlParameter { ParameterName = "@DateMovedIn", Value = address.DateMovedIn.ToString("yyyyMMdd") });
command.Parameters.Add(new SqlParameter { ParameterName = "@Id", Value = address.Id });
command.ExecuteNonQuery();
}
答案 1 :(得分:1)
当参数值为null时会发生这种情况。要修复它,您需要在属性为null时将参数值设置为DbNull。
void AddParameterString(SqlCommand command, string parameterName, string parameterValue)
{
var param = command.Parameters.Add(parameterName, SqlDbType.NVarChar, 4000);
param.Value = String.IsNullOrEmpty(parameterValue) ? (object) DbNull.Value : (object) parameterValue;
}
答案 2 :(得分:0)
您可以简单地使用Null-coalescing运算符(??):
AddParameterString(command, "@AddressLine_2", address.AddressLine_2 ?? Convert.DBNull);