1

My query returns false when some values are null, but my table allows Null values.

What did I do wrong?

cmd.CommandText ="Insert into BusinessTbl(BName,BAddress,BEmail,BMobile,BPhone,Cat_Id)" +
    "values(@bname,@baddress,@bemail,@bmobile,@bphone,@catid)";

cmd.Parameters.AddWithValue("@bname", b.BusinessName);
cmd.Parameters.AddWithValue("@name", b.BusinessAddress);
cmd.Parameters.AddWithValue("@bemail", b.BusinessEmail);
cmd.Parameters.AddWithValue("@bmobile", b.BusinessMobile);
cmd.Parameters.AddWithValue("@bphone", b.BusinessPhone);
cmd.Parameters.AddWithValue("@catid", b.ddlbcategory);

con.ExecuteNonQuery(cmd);

My Table

3
  • 3
    A .Net null is not the same as a database null, if a value is null in your code you need to pass DBNull.Value. Commented Apr 17, 2018 at 10:58
  • Besides the issue at hand, I think you also mean to use "@baddress" instead of "@name". Commented Apr 17, 2018 at 11:09
  • @PeterB good eyes! Commented Apr 17, 2018 at 12:31

1 Answer 1

3

This is a vexing feature of ADO.NET parameters; basically:

cmd.Parameters.AddWithValue("@bname", ((object)b.BusinessName) ?? DBNull.Value);
cmd.Parameters.AddWithValue("@name", ((object)b.BusinessAddress) ?? DBNull.Value);
// etc

should fix you. If the .Value is null, the parameter isn't sent - it needs to be DBNull.Value. Alternatively, a tool like "Dapper" helps avoid this pain:

con.Execute(@"Insert into BusinessTbl(BName,BAddress,BEmail,BMobile,BPhone,Cat_Id)
              values(@bname,@baddress,@bemail,@bmobile,@bphone,@catid)",
   new { bname = b.BusinessName, ... , catid = b.ddlbcategory });

(which will parameterize correctly, including the nulls)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Marc Gravell

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.