我正在尝试动态设置linq数据源的where语句,并且在我尝试添加另一个约束之前它工作正常。
此代码适用于此处:
private void SetDataSourceWhereStatement()
{
HttpCookie cookie = Request.Cookies[ "CustomerID" ];
if ( cookie == null ) //set data source where statement to default
ldsCustomerLinks.Where = "CustomerID == -1";
else ldsCustomerLinks.Where = "CustomerID == " + cookie.Value; //set data source where statement
ldsCustomerLinks.Where = ldsCustomerLinks.Where + " && CategoryID == " + m_CategoryID;
ldsCustomerLinks.DataBind();
}
但是,当我也尝试添加客户编号时,我收到了错误消息。这是我试图使用的代码:
private void SetDataSourceWhereStatement()
{
HttpCookie cookie = Request.Cookies[ "CustomerID" ];
HttpCookie cookie2 = Request.Cookies[ "CustomerNumber" ];
if ( cookie == null ) //set data source where statement to default
ldsCustomerLinks.Where = "CustomerID == -1";
else ldsCustomerLinks.Where = "CustomerID == " + cookie.Value; //set data source where statement
if ( cookie2 != null )
ldsCustomerLinks.Where += " && CustomerNumber == " + cookie2.Value;
// else ldsCustomerLinks.Where += " && CustomerNumber >= 0";
ldsCustomerLinks.Where = ldsCustomerLinks.Where + " && CategoryID == " + m_CategoryID;
ldsCustomerLinks.DataBind();
}
cookie和cookie2值都是字符串。我尝试使用int.parse,int32.parse转换它,使用值的.toString()方法并尝试一切。我不明白什么是错的。
EDIT ::
所以我从下面的一篇文章中得到了我的答案,但我不明白,有人可以解释为什么我的原始代码不起作用但是修改后的吗?
旧代码:
if ( cookie2 != null )
ldsCustomerLinks.Where += " && CustomerNumber == " + cookie2.Value;
新代码:
if ( cookie2 != null )
ldsCustomerLinks.Where += @" && CustomerNumber == (""" + cookie2.Value + @""") ";
答案 0 :(得分:2)
原谅我,在没有太多关于这个LINQ用法的知识的情况下,我的答案可能完全没有了。
This question似乎是相关的,并建议您解析/转换(在这种情况下引用!)值。
答案 1 :(得分:1)
您说cookie
和cookie2
是字符串...... m_CategoryID
怎么办?
你试过吗
ldsCustomerLinks.Where = ldsCustomerLinks.Where + " && CategoryID == " + m_CategoryID.ToString();
好的 - 我怀疑'Where'字符串中CustomerNumber缺少引号,但没有足够的信心将其作为建议发布(有一天糟糕的SO!)
所以回答第二个问题:
类型不匹配来自数据库,其中CustomerNumber(我推断)是一个字符串,但是您正在使用数字构建查询,例如
CustomerID == 312&& CustomerNumber == 45654789&& CategoryID == 3
你应该说
CustomerID == 312&& CustomerNumber ==“45654789”&& CategoryID == 3
要获取字符串中的引号(用引号括起来),您需要使用“”“语法。