0

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.People.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

1

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.