列 [key] 在 dataTable 中抛出 MissingPrimaryKeyException
Column [key] throws MissingPrimaryKeyException in dataTable
var sdr = db.ExecuteReader("SELECT [key],translation FROM language WHERE lang=@lang");
DataTable someTable = new DataTable();
someTable.Load(sdr);
return ((string)(someTable.Rows.Find("[key] = CUSTOMDATEFORMAT").ItemArray[1]));
最后一行现在抛出错误 System.Data.MissingPrimaryKeyException
:"The table has no primary key."
所以我猜它找到了关键字 "key",现在希望我查询主键列,而不是名为 "key" 的列。我如何转义列名?
Find
method is used to find a single rows by the primary key value. Use Select
按任意列值查找行:
DataRow[] foundRows;
foundRows = someTable.Select("[key] = CUSTOMDATEFORMAT");
return foundRows[0].ItemArray[1]; // adding proper bounds checking, of course.
Find
方法使用在 DataTable
对象中指定的列作为 primary key
和 return 包含它在 [= 中获取的值的行13=]单元格。
来自 MSDN:
Gets the row specified by the primary key value.
由于您的 table 没有指定为 primary key
的列,您会收到此错误。
如果您的 key
列保证不包含重复项,您可以使用 DataTable
's PrimaryKey
property.
将其指定为主键
如果没有,则使用 Linq 的 Select
方法代替 find:
return ((string)(someTable.Rows.Select("[key] = CUSTOMDATEFORMAT").ItemArray[1]));
如果你想使用DataRowCollection.Find
you have to specify the DataTable
's PrimaryKey
(s).
我会使用 Linq-To-DataTable
:
DataRow row = someTable.AsEnumerable()
.FirstOrDefault(row => row.Field<string>("key") == "CUSTOMDATEFORMAT");
if(row != null)
return row.Field<string>(1); // or by name but with correct type
else
return "something else";
然后您可以在查询中使用您想要的所有方法。
var sdr = db.ExecuteReader("SELECT [key],translation FROM language WHERE lang=@lang");
DataTable someTable = new DataTable();
someTable.Load(sdr);
return ((string)(someTable.Rows.Find("[key] = CUSTOMDATEFORMAT").ItemArray[1]));
最后一行现在抛出错误 System.Data.MissingPrimaryKeyException
:"The table has no primary key."
所以我猜它找到了关键字 "key",现在希望我查询主键列,而不是名为 "key" 的列。我如何转义列名?
Find
method is used to find a single rows by the primary key value. Use Select
按任意列值查找行:
DataRow[] foundRows;
foundRows = someTable.Select("[key] = CUSTOMDATEFORMAT");
return foundRows[0].ItemArray[1]; // adding proper bounds checking, of course.
Find
方法使用在 DataTable
对象中指定的列作为 primary key
和 return 包含它在 [= 中获取的值的行13=]单元格。
来自 MSDN:
Gets the row specified by the primary key value.
由于您的 table 没有指定为 primary key
的列,您会收到此错误。
如果您的 key
列保证不包含重复项,您可以使用 DataTable
's PrimaryKey
property.
如果没有,则使用 Linq 的 Select
方法代替 find:
return ((string)(someTable.Rows.Select("[key] = CUSTOMDATEFORMAT").ItemArray[1]));
如果你想使用DataRowCollection.Find
you have to specify the DataTable
's PrimaryKey
(s).
我会使用 Linq-To-DataTable
:
DataRow row = someTable.AsEnumerable()
.FirstOrDefault(row => row.Field<string>("key") == "CUSTOMDATEFORMAT");
if(row != null)
return row.Field<string>(1); // or by name but with correct type
else
return "something else";
然后您可以在查询中使用您想要的所有方法。