开发者

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

开发者 https://www.devze.com 2023-02-24 22:35 出处:网络
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. An

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

精彩评论

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