开发者

No records are added to DataTable in Linq Select from DbCommand.ExecuteReader

This code looks like it should work, in fact it compil开发者_如何学运维es and runs. However, the records from the cmd.ExecuetReader() (and there are records,) are not being added to dt as expected. Anyone see what could be missing?

DataTable dt = new DataTable();
cmd.Connection.Open();
cmd.ExecuteReader().Cast<DbDataRecord>().Cast<DataRow>().Select(r=>dt.Rows.Add(r.ItemArray));

Or, is there a more straightforward way of doing this, using linq of course :)


Linq is lazy. It just get executes when you actually access it's data.

This might work:

cmd.Connection.Open();
var data = cmd.ExecuteReader().Cast<DbDataRecord>().Cast<DataRow>().Select(r=>r.ItemArray).ToList();

DataTable dt = new DataTable();

foreach(var d in data)
    dt.Rows.Add(d);

Calling ToList() forces linq to execute

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜