将 DataTable 转换为强类型对象列表
我正在尝试编写一个通用方法,将 DataTable 转换为强类型对象列表。
到目前为止我正在使用的代码是...
public List<T> ImportTable<T>(String fileName, String table)
{
//Establish Connection to Access Database File
var mdbData = new ConnectToAccess(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\ACCESS\" + fileName + ".mdb;");
var tableData = new List<T>();
foreach (DataRow row in mdbData.GetData("SELECT * FROM " + table).Rows)
{
tableData.Add(ConvertRowToType<T>(row));
}
return tableData;
}
public T ConvertRowToType<T>(DataRow row)
{
//??? What is the best thing to do here ???
}
如果有人的建议需要对其进行更改,我不会专注于该代码。
假设我调用此函数并传入类型...
public class mdbConcern
{
public Int32 ConcernId { get; set; }
public String Concern { get; set; }
}
并且 DataTable 中返回的数据看起来像...
ConcernID Concern
1 Law and Ethics
2 Mail
3 Business English
... ...
实现 ConvertRowToType(DataRow row) 方法的最佳方法是什么?
有人可以告诉我如何使用 Func 作为参数之一,以便我可以传递一些映射信息吗?
I am trying to write a generic method that will convert a DataTable to a list of strongly typed objects.
The code that I'm working with so far is...
public List<T> ImportTable<T>(String fileName, String table)
{
//Establish Connection to Access Database File
var mdbData = new ConnectToAccess(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\ACCESS\" + fileName + ".mdb;");
var tableData = new List<T>();
foreach (DataRow row in mdbData.GetData("SELECT * FROM " + table).Rows)
{
tableData.Add(ConvertRowToType<T>(row));
}
return tableData;
}
public T ConvertRowToType<T>(DataRow row)
{
//??? What is the best thing to do here ???
}
I'm not fixated on this code if anybody's suggestions would require changes to it.
So let's say I call this function passing in the type...
public class mdbConcern
{
public Int32 ConcernId { get; set; }
public String Concern { get; set; }
}
And the Data coming back in the DataTable looks like...
ConcernID Concern
1 Law and Ethics
2 Mail
3 Business English
... ...
What would be the best way to implement the ConvertRowToType(DataRow row) method?
Can someone show me how to use Func as one of the parameters so I can pass in some mapping information?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为
扩展方法
是最好的方法:用法:
更新我看到您要求一个
Func
来提供映射。我不确定您到底想做什么,但这是我想出的一种方法:用法:
这是一个使用类型属性上的属性来存储其映射的版本。我认为这是一个更自然的解决方案:
I think an
extension method
is the best way to go:Usage:
Update I see that you asked for a
Func
that would provide the mapping. I'm not sure exactly what you envisioned but here is a method I came up with:Usage:
Here's a version using attributes on the type's properties to store its mapping. I think it's a more natural solution:
除了@Sorax 答案。我增强了
ToType
方法以支持Nullable<>
类型成员(使用字段代替属性,使用TypeInfo
代替TypeDescriptor
>)。它将整个DataTable
对象作为参数并返回IList
。Addition to @Sorax answer. I enhanced
ToType
method to supportNullable<>
type members (using fields instead of properties andTypeInfo
instead ofTypeDescriptor
). It takes wholeDataTable
object as a paramater and returnsIList
.