2012-09-19 72 views
2

尝试创建this linq语句时。我遇到了以下错误:无法将类型为“System.Data.Common.DataRecordInternal”的对象强制类型为“System.Data.IDataReader”

Unable to cast object of type 'System.Data.Common.DataRecordInternal' to type 'System.Data.IDataReader'

这是我每@SLaks promising answer做什么。

List<TypeData> = reader.Cast<IDataReader>() 
    .Select(dr => new TypeData { Type = (string)dr["type"] })     
    .ToList(); 
+1

你可以发布你的'TypeData'类的代码结构? – jp2code

+0

另外,看起来你正在设置TypeData obj = xxx.ToList()。 – jp2code

回答

6

尝试reader.Cast<DbDataRecord>reader.Cast<IDataRecord>代替:

IEnumerable<TypeData> typeData = reader.Cast<IDataRecord>() 
    .Select(dr => new TypeData { Type = (string)dr["type"] }); 

IDataRecord Interface

Provides access to the column values within each row for a DataReader, and is implemented by .NET Framework data providers that access relational databases.

+0

他还需要某种'SingleOrDefault'而不是'ToList'吗? – jp2code

+0

这工作!谢谢...两分钟,直到我可以给你信用。 – capdragon

+0

@ jp2code:是的,我已经删除了“ToList”,而是使用了“IEnumerable ”。 –

相关问题