最佳实践:创建数据访问类
我有以下类,用于从 Access 数据库读取大量数据。
public class ConnectToAccess
{
private readonly string _connectionString;
public ConnectToAccess(String connectionString)
{
_connectionString = connectionString;
}
public List<String> GetData(String sql)
{
var data = new List<String>();
using (var connection = new OleDbConnection(_connectionString))
{
using (var command = connection.CreateCommand())
{
command.CommandText = sql;
command.CommandType = CommandType.Text;
connection.Open();
using (var reader = command.ExecuteReader())
{
if (reader != null && reader.HasRows)
while (reader.Read())
{
data.Add(reader["First Name"] + " " + reader["Last Name"]);
}
}
}
}
return data;
}
}
按原样,此代码正在运行并成功从数据库中提取数据。但是,我想增强 GetData() 方法以使其更加动态。我希望它以某种方式返回匿名对象的列表,其中每个对象都具有与返回的数据集的列相关的属性。
我已经在 .Net 中编码有一段时间了,但我对许多概念仍然相当陌生。我不太确定如何创建最有效地镜像数据集中的列的匿名对象列表。我也不确定在这种情况下我会使用什么返回类型,我想也许是 List。然后我想我需要使用反射从这些匿名对象中提取数据并将其传输到需要的地方。
如果有人能帮助我解决这个难题的任何重要部分,我将不胜感激。
I have the following class which I am using to read in large amounts of data from an Access database.
public class ConnectToAccess
{
private readonly string _connectionString;
public ConnectToAccess(String connectionString)
{
_connectionString = connectionString;
}
public List<String> GetData(String sql)
{
var data = new List<String>();
using (var connection = new OleDbConnection(_connectionString))
{
using (var command = connection.CreateCommand())
{
command.CommandText = sql;
command.CommandType = CommandType.Text;
connection.Open();
using (var reader = command.ExecuteReader())
{
if (reader != null && reader.HasRows)
while (reader.Read())
{
data.Add(reader["First Name"] + " " + reader["Last Name"]);
}
}
}
}
return data;
}
}
As is, this code is working and is successfully pulling data in from the database. However, I would like to enhance the GetData() method to make it more dynamic. I would like it to somehow return a list of anonymous objects, where each object has properties relating to the columns of the dataset returned.
I've been coding in .Net for a while, but I'm still rather new at many concepts. I'm not quite sure how to create this list of anonymous objects that mirror the columns in the dataset most effectively. I'm also not sure what return type I would use in this case, I'm thinking maybe List. Then I suppose I would need to use reflection to pull the data out of those anonymous objects and transfer it into where it needs to go.
If anyone can help me with any significant part of this puzzle, I would be most obliged.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不能将匿名类型作为返回类型。
为什么不直接返回一个 DataTable。您甚至可以使用 DataAdapter 来使该过程变得更加容易。它还可以为您提供架构。
如果您坚持获取所有内容的对象:
现在您可以将它与选择器一起使用:
You can't have an anonymous type as a return type.
Why not just return a DataTable. You can even use a DataAdapter to make the process a lot easier. It also gets you the schema.
If you insist on getting objects for everything:
Now you can use it with a selector: