gpt4 book ai didi

c# - 使用 Reflection 和 IDataReader.GetSchemaTable 创建读取和处理 IDataReader 当前结果集的通用方法时出现的问题

转载 作者:太空宇宙 更新时间:2023-11-03 11:34:52 24 4
gpt4 key购买 nike

我正在编写一个类,它封装了使用 ADO.NET 从数据库中检索数据的复杂性。其核心方法是

private void Read<T>(Action<T> action) where T : class, new() {
var matches = new LinkedList<KeyValuePair<int, PropertyInfo>>();

// Read the current result set's metadata.
using (DataTable schema = this.reader.GetSchemaTable()) {
DataRowCollection fields = schema.Rows;

// Retrieve the target type's properties.
// This is functionally equivalent to typeof(T).GetProperties(), but
// previously retrieved PropertyInfo[]s are memoized for efficiency.
var properties = ReflectionHelper.GetProperties(typeof(T));

// Attempt to match the target type's columns...
foreach (PropertyInfo property in properties) {
string name = property.Name;
Type type = property.PropertyType;

// ... with the current result set's fields...
foreach (DataRow field in fields) {

// ... according to their names and types.
if ((string)field["ColumnName"] == name && field["DataType"] == type) {

// Store all successful matches in memory.
matches.AddLast(new KeyValuePair<int, PropertyInfo>((int)field["ColumnOrdinal"], property));
fields.Remove(field);
break;
}
}
}
}

// For each row, create an instance of the target type and set its
// properties to the row's values for their matched fields.
while (this.reader.Read()) {
T result = new T();
foreach (var match in matches)
match.Value.SetValue(result, this.reader[match.Key], null);
action(result);
}

// Go to the next result set.
this.reader.NextResult();
}

关于该方法的正确性,不幸的是我现在无法测试,我有以下问题:

  1. 当单个 IDataReader用于从两个或多个结果集中检索数据,IDataReader.GetSchemaTable返回所有结果集的元数据,还是只返回当前结果集对应的元数据?

  2. 列序号是否由 IDataReader.GetSchemaTable 检索等于索引器使用的序数 IDataReader[int] ?如果不是,有没有办法将前者映射到后者?

关于该方法的效率,我有以下问题:

  1. 什么是 DataRowCollection的底层数据结构?即使这个问题不能回答,至少,删除 DataRow 的渐近计算复杂度是多少?来自DataRowCollection使用 DataRowCollection.Remove()

而且,关于该方法的明显丑陋,我有以下问题:

  1. 有没有办法从 IDataReader 中检索特定的元数据(例如,仅列的序号、名称和类型),而不是完整的模式表? ?

  2. 是对 string 的转换在(string)field["ColumnName"] == name必要的? .NET 如何比较 object恰好包含对 string 的引用的变量到 string变量:按引用值还是按内部数据值? (当有疑问时,我更愿意在正确性方面犯错,因此会犯错误;但是,当能够消除所有怀疑时,我更愿意这样做。)

  3. 即使我使用的是 KeyValuePair<int, PropertyInfo> s 表示匹配的字段和属性对,这些对不是实际的键值对。它们只是普通的二元组。但是,.NET Framework 2.0 版不提供元组数据类型,如果我要创建自己的专用元组,我仍然不知道在哪里声明它。在 C++ 中,最自然的地方是在方法内部。但这是 C#,方法内类型定义是非法的。我应该怎么办?应对使用根据定义不是最合适的类型 (KeyValuePair<int, PropertyInfo>) 的不雅之处,还是应对无法声明最适合的类型?

最佳答案

就 A1 而言,我相信在调用 IDataReader.NextResult() 之前,GetSchemaTable 只会返回当前结果集的信息。

然后当调用 NextResult() 时,您必须再次执行 GetSchemaTable 以获取有关当前结果集的信息。

HTH.

关于c# - 使用 Reflection 和 IDataReader.GetSchemaTable 创建读取和处理 IDataReader 当前结果集的通用方法时出现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6628816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com