Home > Enterprise >  LINQ on DataRelationCollection (DataSet.Relations)
LINQ on DataRelationCollection (DataSet.Relations)

Time:12-13

While working on an app that will import XML to SQL Server. XML has a structure like in this question: How to get multiple tables in Dataset from XML

I'm able to load XML into DataSet and get the correct tables using the above code:

var ds = new DataSet();
var employees = new DataTable("Employees");
var cars = new DataTable("Cars");
//and others

using Stream stream = new FileStream("data.xml", FileMode.Open, FileAccess.Read);
ds.ReadXml(stream);

foreach (DataRelation dataRelation in ds.Relations)
{
    switch (dataRelation.ParentTable.TableName)
    {
        case "Employees":
            employees = dataRelation.ChildTable;
            break;
        case "Cars":
            cars = dataRelation.ChildTable;
            break;
        //and others
    }
}

but when I try to do a similar thing with LINQ:

var dt1 = ds.Relations.Where(x => x.RelationName == "Employees").FirstOrDefault();

I get this error:

Error CS1061 'DataRelationCollection' does not contain a definition for 'Where' and no accessible extension method 'Where' accepting a first argument of type 'DataRelationCollection' could be found (are you missing a using directive or an assembly reference?)

Is there a better way to get a specific DataTable from DataSet (by using DataRelation)?

CodePudding user response:

DataRelationCollection implements only non-generic version of ICollection (inherited from InternalDataCollectionBase ) which is quite limited in terms of LINQ methods supported, you can "enable" generic methods via OfType call:

var dt1 = dataRelationCollection.OfType<DataRelation>()
    .FirstOrDefault(x => x.RelationName == "Employees");
  • Related