将数据表映射到列表 的 LINQ
我刚刚发现 LINQ,所以请对我进行全面的了解! :-)
所以!我有一个数据层,它为我提供数据表,我想将它们转换为对象列表。这些对象在特定层DTO(数据传输对象)中定义。
如何将数据表的每一行映射到对象并将所有对象放入列表中? (今天我“手动”逐个字段地进行) 可以用LINQ吗?我听说过 LINQ2Entities?我说得对吗?
感谢帮助初学者理解...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果对象不是太复杂,您可以使用它:
现在您可以编写:
var list = YourDataTable.ToList()
。您可以在这里阅读:http://blog.tomasjansson。 com/convert-datatable-to-generic-list-extension/
这是对上一个问题的答案:将 DataTable 转换为 C# 中的通用列表
编辑: 我应该补充一点,这不是 linq,而是
DataTable我写的。此外,它还遵循约定,即您要映射的对象中的属性与数据表中的属性具有相同的名称。当然,这可以扩展为读取属性上的属性,或者方法本身可以采用可用于执行映射的简单的
Dictionary
。您还可以使用一些功能来扩展它,这些功能采用可用于排除某些属性的params string[] exceptProperties
。If the objects is not too complex you can use this:
With that in place you can now write:
var list = YourDataTable.ToList<YourEntityType>()
.You can read about it here: http://blog.tomasjansson.com/convert-datatable-to-generic-list-extension/
And it is an answer to a previous question: Convert DataTable to Generic List in C#
EDIT: I should add that this is not linq, but some extension methods to
DataTable
I wrote. Also, it is working with the convention that the properties in the object you're mapping with has the same name as in the DataTable. Of course this could be extended to read attributes on the properties or the method itself could take a simpleDictionary<string,string>
that could be used to do the mapping. You could also extend it with some functionality that take aparams string[] excludeProperties
that could be used to exclude some of the properties.我建议阅读ADO.NET 实体框架。它支持您所要求的内容,并且该链接应该为您提供足够的信息和示例:)
还有 有大量关于该主题的教程可以帮助您入门。
I would suggest reading about The ADO.NET Entity Framework. It supports what you're asking, and the link should provide you with sufficient information and examples :)
There are also plenty of tutorials out there about the topic to get you started.
最好检查该列是否存在于行中以另一种方式进行映射,它将引发异常,在我的情况下,我有两个对象,其中一个比另一个具有相同名称和数据类型的属性更多
it's better to Check if the column exist in the row to do the mapping another way it will throw an exception, in my case I have two objects one of them have more proprieties than the other with the same name and data type