LINQ到数据表简便而快捷 [英] LINQ to DataTable Easy and Fast
问题描述
我是新来的LINQ,我想LINQ查询转换为数据表
I am new to LINQ, I want to convert LINQ query to DataTable
DataClassesDataContext db = new DataClassesDataContext(MyConncectionString);
IEnumerable<DataRow> qry = (IEnumerable<DataRow>)(from tbl in db.Table1.AsEnumerable()
select tbl);
DataTable dt=new DataTable();
qry.CopyToDataTable(dt, LoadOption.OverwriteChanges);
GridView1.DataSource = dt;
但我得到的错误
<块引用>
无法转换类型'WhereSelectEnumerableIterator键入System.Collections.Generic.IEnumerable`1 [的System.Data.DataRow]'的对象。
块引用>
任何人都可以请帮我,
推荐答案
这些都是基本的概念:
有附带使用.NET Framework几个LINQ提供程序
There are several LINQ providers shipped with the .Net framework
-
LINQ到对象。 System.Linq的。这是LINQ核心部分,它在设计时内存中的集合工作
LINQ to Objects. System.Linq. It's the LINQ core and it is designed to work with in-memory collections
的LINQ to XML。 System.Xml.Linq的要使用XML文档
LINQ to XML. System.Xml.Linq To work with XML documents
LINQ到数据集。要与数据表工作,数据集对象
LINQ to DataSet. To work with DataTable, and DataSet objects
LINQ to SQL的。将System.Data.Linq它是用来与SQL Server数据库的工作
LINQ to SQL. System.Data.Linq It is used to work with SQL Server databases
LINQ到实体。 (实体框架)用于与多个数据库工作。它提供了一个更丰富的API
LINQ to Entities. (Entity Framework) Used to work with several databases. It provides a richer API
我认为你正在试图做的是:
What I think you are trying to do is:
的从从LINQ返回到SQL上下文的查询时,要返回的DataRow
对象的集合。的
From a query returned from a LINQ to SQL context, you want to return a collection of DataRow
objects.
有到SQL对象和一个DataRow一个LINQ之间不存在简单的转换,因此,如果你坚持,你需要使用反射来获取所需的输出的使用来自LINQ查询填写的DataTable的最快方法的DataContext
现在,如果你真的想用DataTable对象的工作,那么我的建议是使用强类型DataSet。要创建一个,只是一个新的DataSet对象添加到您的项目,并从服务器资源管理器拖放表就像你与你的LINQ to SQL对象
Now if you really want to work with the DataTable objects, then my recommendation is to use a strongly typed DataSet. To create one, simply add a new DataSet object to your project and from the Server Explorer drag tables like you would do with your LINQ to SQL objects
如果可能的话,评估使用的DataRow
,而是返回由生成LINQ到SQL对象的决定,甚至更好的创建自定义的DTO对象
If possible, evaluate the decision to use DataRow
and instead return the objects generated by LINQ To SQL, or even better create your custom DTO objects
关于您的code,我看不出有任何理由要尝试使用数据表
对象(除非你是n要发布额外的code到证明这个决定)。如果你只是想设置控件的数据源
属性,只需做到以下几点:
About your code, I don't see any reason to try to use a Datatable
object (unless you are nto posting that extra code to justify this decision). If you just want to set the DataSource
property of a control, simply do the following:
var q = from tbl in db.Table1
select tbl;
this.myControl.DataSource = q;
this.myControl.DataBind();
如果您有需要,您可以将结果放入一个匿名对象,并用它作为数据源
:
If you need, you can transform the result into an anonymous object and used it as the DataSource
:
var q = from tbl in db.Table1
select new
{
MyNewProperty = tbl.ExistingProperty,
AnotherProperty = tbl.MyCoolerProperty
};
this.myControl.DataSource = q;
this.myControl.DataBind();
这篇关于LINQ到数据表简便而快捷的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!