无法在varbinary(max)中插入null值并出现错误:不允许从数据类型nvarchar到varbinary(max)的隐式转换

时间:2017-04-25 20:03:55

标签: c#

我想在varbinary(max)中插入null值,但它返回错误。

我正在尝试下面的代码来保存照片,当我附加照片时,它保存没有任何问题。没有照片时会抛出错误。

  

从数据类型nvarchar到varbinary(max)的隐式转换不是   允许。使用CONVERT函数运行此查询。

protected void Button3_Click(object sender, EventArgs e)
{
    newphoto pat = new newphoto();
    pat.id = id.Text;
    byte[] photo = null;
    if (Attch.HasFile)
    {
        Stream fs2 = Attch.PostedFile.InputStream;
        BinaryReader br2 = new BinaryReader(fs2);
        pat.photo = br2.ReadBytes((Int32)fs2.Length);
    }
    else
    {
        pat.photo = null;
    }
    pat.Addfile()
}

public bool Addfile()
{
    Parameters.Clear();
    Parameters.AddWithValue("@pat_id", id);
    if (photo == null)
    {
        Parameters.Add("@photo", SqlDbType.VarBinary, -1);
        Parameters["@photo"].Value = DBNull.Value;
    }
    else
    {
        Parameters.AddWithValue("@photo", photo);
    }
    return FetchNonQuery(@"insert into mr_Info (@pat_id ,@photo)" +
               " Values (@pat_id ,@photo)");
}

protected bool FetchNonQuery(string CmdQuery)
{
    bool result = false;
    using (SqlConnection myConnection = DBConnection)
    {
        SqlCommand myCommand = new SqlCommand(CmdQuery, myConnection);
        myCommand.CommandType = CommandType.Text;
        //Set Parameters       
        foreach (SqlParameter Parameter in _parameters)
        {
            myCommand.Parameters.AddWithValue(Parameter.ParameterName, Parameter.Value);
        }
        //Execute the command
        myConnection.Open();
        if (myCommand.ExecuteNonQuery() > 0)
        {
            result = true;
        }
        myConnection.Close();
    }
    return result;
}

1 个答案:

答案 0 :(得分:2)

这是AddWithValue调用引起的一个微妙的错误。 (和not the only one) 当AddWithValue能够正确识别参数的类型时,您没有问题,但是当您将参数值设置为DBNull.Value时,该方法会尝试将其转换为字符串,并且您会收到错误,因为数据字段需要一个多样性。
但是,在构建参数列表时,您可以准确指定预期的类型,因此您只需将参数传递给Add方法,而不是使用AddWithValue构建另一个参数。

foreach (SqlParameter Parameter in _parameters)
{
    myCommand.Parameters.Add(Parameter);
}

您甚至可以使用

删除循环
myCommand.Parameters.AddRange(_parameters.ToArray());

另外,正如我在其他评论中指出的那样,INSERT命令应写为

INSERT INTO (pat_id,photo) VALUES (@pat_id ,@photo)