开发者

Creating Datatable from object type LINQ

I'm using entity framework 4.0. I'm trying to create a DataTable from the Table in my database using LINQ query at runtime. Here is a code:

var result = from r in DbContext.Peopl开发者_运维知识库e.AsEnumerable()
      select new { r.PersonID, r.FirstName, r.LastName };

I'm getting data in my result variable.

IEnumerable<DataRow> drs = result as IEnumerable<DataRow>; // This line returns null

I'm not getting datarows in drs variable. After doing the above operation how can I create datatable using LoadDataRow() method of datatable.

Please let me know what I'm doing wrong here.

Thanks in advance


By doing this:

select new { r.PersonID, r.FirstName, r.LastName };

You're making an anonymous type. This is not a DataRow, which is why your conversion fails.

You'll need to make your new DataTable, then populate it (in a foreach loop or similar) with the results stored in result. You can't just directly cast this into a DataRow.


The result will not be an enumerable of DataRows; it will instead be an enumerable of anonymous types, which do not explicitly cast to DataRow in any case. To convert the anonymous type to a DataRow, you will have to first create a DataTable with the column names, then for each instance of the anonymous type, add a new DataRow to the DataTable. You cannot instantiate new DataRows explicitly; the structure of a DataRow object is completely dependent upon its parent DataTable.


First, I'll assume, that DbContext is EF4 context to database. Then first thing is, you don't need to call AsEnumerable() method, just simply query the People table.

Second, you're returning anonymous type, not a DataRow. When returning from EF4 query, you can simply return r variable, and it will be instance of People class, that you can use further in your program. If you need DataRow you need to create it by hand, but I would suggest to stick with objects created by EF4, if possible.

After all of that, remember, that while querying database, delayed execution takes place. This means, that query will not run before you will use it in foreach loop or call some methods like First, Single or ToList() on this result. If you need your results immediately, add ToList() at end of query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜