在使用linq将空值传递给ExecuteCommand()方法时,我遇到了一个问题。我的代码类似于下面的代码:
public void InsertCostumer(string name, int age, string address)
{
List<object> myList = new List<object>();
myList.Add(name);
myList.Add(age);
myList.Add(address);
StringBuilder queryInsert = new StringBuilder();
queryInsert.Append("insert into Customers(name, address) values ({0}, {1}, {2})");
this.myDataContext.ExecuteCommand(queryInsert.ToString(), myList.ToArray());
}
但是,当参数为空(例如,地址)时,我会得到以下错误:“查询参数不能是‘System.Object’类型。”
如果没有参数为空,则不会发生错误。我知道我的例子中的设计有点差,我只是创建了一个简单的例子来关注这个问题。有什么建议吗?
发布于 2014-02-18 23:22:58
我通常使用这类东西,不是很理想,但如果你遇到困难,它就能解决问题
if (myObject != null)
{
foreach (var p in ct.GetType().GetProperties())
{
if (p.GetValue(myObject , null) == null)
{
if (p.PropertyType == typeof(string))
{
p.SetValue(myObject , "Empty", null);
}
if (p.PropertyType == typeof(int))
{
p.SetValue(myObject , 0, null);
}
if (p.PropertyType == typeof(int?))
{
p.SetValue(myObject , 0, null);
}
}
}
}
这确保在使用ExecuteCommand中的参数之前,对象中的每个值都有一个值。再说一次,这不是理想的,但它是有效的。
https://stackoverflow.com/questions/859985
复制相似问题