Reputation: 25
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);
Upvotes: 1
Views: 52
Reputation: 1062810
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 null
s)
Upvotes: 3