当某些值为null时,我的查询返回false,但我的表允许Null值。
我做错了什么?
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);
答案 0 :(得分:3)
这是ADO.NET参数的一个令人烦恼的功能;基本上是:
cmd.Parameters.AddWithValue("@bname", ((object)b.BusinessName) ?? DBNull.Value);
cmd.Parameters.AddWithValue("@name", ((object)b.BusinessAddress) ?? DBNull.Value);
// etc
应该修复你。如果.Value
为null
,则不会发送参数 - 它必须为DBNull.Value
。或者,像"Dapper"这样的工具有助于避免这种痛苦:
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 });
(将正确参数化,包括null
s)