参数化查询需要未提供的参数 [英] The parameterized query expects the parameter , which was not supplied

查看:48
本文介绍了参数化查询需要未提供的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MVC应用程序中有一种方法

in my MVC application there is a method

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 时,出现错误:

AddressLine2 in model is not required. When user is not submitting AddressLine2 I get error:

参数化查询'(@ AddressLine_1 nvarchar(3),@ AddressLine_2nvarchar(4000),@ Postc'需要参数'@ AddressLine_2'没有提供.

The parameterized query '(@AddressLine_1 nvarchar(3),@AddressLine_2 nvarchar(4000),@Postc' expects the parameter '@AddressLine_2', which was not supplied.

如何修改此方法在两种情况下均有效-用户提交 AddressLine2 和用户不提交 AddressLine2 ?

How can I modify this method to work in both cases - user submitting AddressLine2 and user not submitting AddressLine2?

推荐答案

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();
}

这篇关于参数化查询需要未提供的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆