类的静态构造函数 SourceManager
遍历所有模块/类并发现所有实现 ISource
的类.它将实例化其中的每一个并公开一个 IEnumerable
。它们作为一个名为 IEnumerable<ISource> Sources
的静态属性.为简单起见 ISource
有两个属性,DataTable Table { get; }
和 string UniqueName { get; }
.实例化时各不相同ISource
负责填充其 Table
来自 SQL、MDX 等。对于所有 ISource
到目前为止,我已经写好了,正在加载 Table
所有 DataRow
s 实例化时已经足够了。然而,我现在有一种情况,我想加载 Table
与 DataRow
是懒惰的,而不是全部在前面。我该怎么做?我将通过一个例子来说明。
PermissionSource
工具 ISource
.它的Table
属性,具有 private set
的值为 new PermissionDataTable()
.它的UniqueName
是"Permissions"
.截至目前,没有权限从数据库加载到此 Table
属性(property)。
ISource permissionSource = SourceManager.Sources.
Where(s => "Permission".Equals(s.UniqueName)).First();
现在我们已经获得了PermissionSource
,而是通过一个接口(interface)。让我们获得许可。
DataRow row = permissionSource.Table.Rows.Cast<DataRow>().
Where(r => r["PermissionName"].Equals("PermissionName")).First()
我已经覆盖了 Rows
属性(property) PermissionDataTable
这样上面的代码就以某种方式获得了与 "PermissionName"
关联的权限的值。在数据库中。其他权限未加载。
我在权限系统中没有选择,我也没有选择不使用 DataTable
.
编辑:
在我的示例中,我需要覆盖 Rows
DataTable
的属性(property). Rows
, 不过, 是 DataRowCollection这是 sealed
.因此,就创建一个像我想做的那样的最小自定义 DataTable 实现而言,可以做的事情并不多。
最佳答案
我不确定我是否理解您在使用 DataTable 时的限制,但是我过去在需要“刷新”DataTable 中的数据或使用不同的标准重新填充数据时做过的一件事是创建一个新类派生自 DataTable,其中包括对 DataAdapter 的引用以及最初用于填充 DataTable 的连接和选择信息。
例如,DataTable 子类可能类似于下面的 LazyDataTable
代码。请注意,我添加了几种不同的访问行的方法。在查看接近本文末尾的 PermissionSource
和主要 Program
代码后,它们可能更有意义。 另外,请注意,我并没有包括在每种情况下正确打开和关闭数据库连接的所有细节。您如何处理这取决于您的数据库访问模型(例如连接池、共享连接等)。
//using System.Data.Common;
public class LazyDataTable : DataTable {
protected DbDataAdapter Adapter { get; set; }
public LazyDataTable(DbDataAdapter a) {
Adapter = a;
}
/// <summary>
/// Save changes back to the database, using the DataAdapter
/// </summary>
public void Update() {
Adapter.Update(this);
}
/// <summary>
/// Fill this datatable using the SelectCommand in the DataAdapter
/// The DB connection and query have already been set.
/// </summary>
public void Fill() {
Adapter.Fill(this);
}
/// <summary>
/// read and return one row at a time, using IEnumerable syntax
/// (this example does not actually add the row to this table,
/// but that can be done as well, if desired.
/// </summary>
public IEnumerable<DataRow> LazyReadRows() {
using (var reader = OpenReader()) {
//Get the schema from the reader and copy it to this table.
var schema = reader.GetSchemaTable();
var values = new object[schema.Columns.Count];
while (reader.Read()) {
reader.GetValues(values);
var row = schema.NewRow();
row.ItemArray = values;
yield return row;
}
}
}
/// <summary>
/// Fill one row at a time, and return the new row.
/// </summary>
public DataRow ReadRow() {
if (_reader == null || _reader.IsClosed)
_reader = OpenReader();
//Get the schema from the reader and copy it to this table.
if (this.Columns.Count == 0)
this.Columns.AddRange(_reader.GetSchemaTable().Columns.Cast<DataColumn>().ToArray());
if (!_reader.Read()) {
_reader.Dispose();
return null;
}
var values = new object[_reader.FieldCount];
_reader.GetValues(values);
return this.Rows.Add(values);
}
private DbDataReader _reader = null;
private DbDataReader OpenReader() {
OpenConnect();
return Adapter.SelectCommand.ExecuteReader();
}
private void OpenConnect() {
var cn = Adapter.SelectCommand.Connection;
if (cn.State == ConnectionState.Closed)
cn.Open();
}
/// <summary>
/// Change a Parameter in the SelectCommand, to filter which rows to retrieve.
/// </summary>
public void SetSelectParam(string name, object value) {
var selparams = Adapter.SelectCommand.Parameters;
selparams[name].Value = value;
}
}
然后您的 PermissionSource
将创建一个 LazyDataTable
并适本地设置 DataAdapter(包括连接和 SELECT 命令)。它不会填充 DataTable,而是将其返回为空,稍后由应用程序代码填充。所以你的 PermissionSource
可能类似于下面的代码。我使用 System.Data.OleDb
数据对象作为示例,但您可以使用所需的任何 ADO 提供程序。
interface ISource {
public DataTable Table { get; }
string UniqueName { get; }
}
public class PermissionSource : ISource {
/// <summary>
/// Loads a DataTable with all of the information to load it lazily.
/// </summary>
public DataTable Table {
get {
const string SELECT_CMD = "SELECT * FROM [Permissions] WHERE ([PermissionName] IS NULL OR [PermissionName]=@p1) AND [OtherProperty]=@p2";
var conn = new OleDbConnection("...ConnectionString...");
var selectCmd = new OleDbCommand(SELECT_CMD, conn);
selectCmd.Parameters.AddWithValue("p1", "PermissionName");
selectCmd.Parameters.AddWithValue("p2", 0);
var adapter = new OleDbDataAdapter(selectCmd);
var builder = new OleDbCommandBuilder(adapter); //used to generate the UPDATE and DELETE commands...
adapter.UpdateCommand = builder.GetUpdateCommand(); //etc.
//Do NOT fill the table here. Instead, let the caller fill it.
return new LazyDataTable(adapter);
}
}
public string UniqueName { get { return "Permission"; } }
}
您的主程序代码将使用 PermissionSource
和 LazyDataTable
,如下所示:
static class Program {
void GetPermissions() {
ISource permissionSource = SourceManager.Sources.
Where(s => "Permission".Equals(s.UniqueName)).First();
var table = permissionSource.Table as LazyDataTable;
table.SetSelectParam("PermissionName", "Admin");
//If you want to fill ALL rows in one step:
table.Fill();
// OR If you want to fill one row at a time, and add it to the table:
DataRow row;
while(null != (row = table.ReadRow())) {
//do something with each individual row. Exit whenever desired.
Console.WriteLine(row["PermissionName"]);
}
// OR If you prefer IEnumerable semantics:
DataRow row = table.LazyReadRows().FirstOrDefault(someValue.Equals(row["columnname"]));
//OR use foreach, etc. Rows are still ONLY read one at a time, each time IEnumerator.MoveNext() is called.
foreach (var row in table.LazyReadRows())
if (row["someColumn"] == "someValue")
DoSomething(row["anothercolumn"]);
}
}
您当然可以混合和匹配此处显示的 LazyDataTable 的各个部分,以在您的应用程序限制范围内实现您想要的。如果您可以切换到不同的共享数据模型当然会好得多,但是如果您必须从每个源返回一个 DataTable,那么至少您可以在必要时返回一个功能更强大的 DataTable正如我在这里演示的那样对其进行子类化。这使您可以传回更多信息,您可以根据需要使用这些信息来填充表格。
我仍然鼓励您查看 LinqToSQL 以及可能尝试切换到简单地传回 DbDataReader 或类似于我在此处显示的 LazyDataTable 的其他一些对象,这将允许您自定义原始查询(例如,通过使用SetSelectParam
方法)以及一次读取一行中的数据。
希望对您有所帮助!
关于c# - 在 C# 中扩展 DataTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12162235/