1

I am getting error while trying to loop through query object using var variable in foreach construct. I am loading xml in to dataset and performing Dataset to Linq for explicit reasons. Please correct my mistake. This is my code:

ds.ReadXml(fsReadXml);

DataTable myDataTable = ds.Tables[0];

var ordersQuery = myDataTable.AsEnumerable();

var subQuery = (from Geo03 in ordersQuery
                select new
                {
                    PARENTTYPE = Geo03.Field<String>("PARENTTYPE"),
                    PARENTINSTANCE = Geo03.Field<int>("PARENTINSTANCE"),
                    CHILDTYPE = Geo03.Field<String>("CHILDTYPE"), 
                    CHILDINSTANCE = Geo03.Field<String>("CHILDINSTANCE"),
                    CHILDPOS = Convert.ToInt32(Geo03.Field<int>("CHILDPOS"))
});
XDocument doc = null;
foreach (var cin in subQuery)
{


}

This is the generated error:

System.InvalidCastException: Specified cast is not valid.
   at System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value)
   at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)
   at SpectraWorkon.Program.<Main>b__0(DataRow Geo03) in c:\users\arun\documents\visual studio 2010\Projects\SpectraWorkon\SpectraWorkon\Program.cs:line 29
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at SpectraWorkon.Program.Main(String[] args) in c:\users\arun\documents\visual studio 2010\Projects\SpectraWorkon\SpectraWorkon\Program.cs:line 38

I am getting error for the line foreach (var cin in subQuery), saying it is unable to cast.

user1061293
  • 167
  • 1
  • 4
  • 14

2 Answers2

5

You're calling Field<int> on a field that isn't an int.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

Have in mind that the linq query isn't executed until you actually use it(for example in a foreach loop, or you call .ToList()). So in your case the exception is in the part where you build your query. The InvaliCastException suggests that you are filling a field that is not the type that you expect it to be. So I would suggest that you check the types of the Field<T> in your query.

TheBoyan
  • 6,802
  • 3
  • 45
  • 61
  • +1 for deeper explanation. (the stacktrace explicitly says it's from `Field`, but doesn't say how) – SLaks Dec 21 '11 at 00:32