带有Guids的DataTable Select()
题
我试图在运行时从LINQ查询返回的DataTable中提取我的树视图。返回的字段是:
NAME = CaseNoteID | ContactDate | ParentNote TYPE = Guid | DateTime | GUID
ParentNote字段与CaseNoteID列中的条目匹配。选择(过滤器)给我一个 的运行时错误找不到列[ea8428e4]。 该字母数字是其中一个Guids的第一部分。当我通过我的代码过滤器= " ParentNote = ea8428e4-1274-42e8-a31c-f57dc2f189a4"
我错过了什么?
var tmpCNoteID = dr["CaseNoteID"].ToString();
var filter = "ParentNote="+tmpCNoteID;
DataRow[] childRows = cNoteDT.Select(filter);
解决方案
尝试用单引号括起GUID:
var filter = "ParentNote='"+tmpCNoteID+"'";
其他提示
这应该有效:
var tmpCNoteID = dr["CaseNoteID"].ToString();
var filter = "ParentNote=\""+tmpCNoteID+"\"";
DataRow[] childRows = cNoteDT.Select(filter);
我知道这是一个老线程,但我想添加一个附录。当使用带有Guid的IN运算符(例如:ParentNote IN(,等))时,不再接受单引号。在这种情况下,CONVERT方法(由granadaCoder建议)是必要的。 (单引号引发了一个例外,即将Guid与带有'='运算符的字符串进行比较...我们实际上没有使用它。)
详细信息:我继承了以下格式构建大型过滤字符串的遗留代码: MyColumn ='11111111-2222-3333-4444-555555555555'Or MyColumn ='11111111-2222 -3333-4444-555555555555'....
当guid的数量(以及因此OR子句的数量)变得太大时,这会导致堆栈溢出异常。通过用IN子句替换大量OR子句,我能够设置过滤器而没有异常。但是使用IN子句意味着必须使用CONVERT方法。
这是我使用的一种方法:
MyStrongDataSet ds = new MyStrongDataSet();
Guid myUuid = new Guid("11111111-2222-3333-4444-555555555555");
System.Data.DataRow[] rows = ds.MyStrongTable.Select("MyGuidProperty = (CONVERT('" + myUuid.ToString("N") + "', 'System.Guid'))");
//Fish out a single row if need be and cast to a strong row
if (null != rows)
{
if (rows.Length > 0)
{
MyStrongDataSet.MyStrongTableRow returnRow = rows[0] as MyStrongDataSet.MyStrongTableRow;
return returnRow;
}
}
return null;
这是一个小小的变化:
string filterSql = "MyGuidProperty ='{0}'";
filterSql = string.Format(filterSql, Guid.NewGuid().ToString("D"));
不隶属于 StackOverflow