The parameterized query … expects the parameter '@units', which was not supplied

后端 未结 5 2024
耶瑟儿~
耶瑟儿~ 2020-12-01 10:02

I\'m getting this exception:

The parameterized query \'(@Name nvarchar(8),@type nvarchar(8),@units nvarchar(4000),@rang\' expects the parameter \'@uni

5条回答
  •  庸人自扰
    2020-12-01 10:38

    This extension class was useful to me a couple of times so far, for those issues:

    public static class DbValueExtensions
    {
        // Used to convert values coming from the db
        public static T As(this object source)
        {
            return source == null || source == DBNull.Value
                ? default(T)
                : (T)source;
        }
    
        // Used to convert values going to the db
        public static object AsDbValue(this object source)
        {
            return source ?? DBNull.Value;
        }
    }
    

    You would normally use it in two scenarios. First, when creating parameters for your query:

    var parameters = new Dictionary
    {
        { "@username", username.AsDbValue() },
        { "@password", password.AsDbValue() },
        { "@birthDate", birthDate.AsDbValue() },
    };
    

    or when parsing the SqlReader values:

    while (reader.Read())
    {
        yield return new UserInfo(
            reader["username"].As(),
            reader["birthDate"].As(),
            reader["graduationDate"].As(),
            reader["nickname"].As()
        );
    }
    

提交回复
热议问题