views:

873

answers:

2

How can I use Linq with Dataset.xsd files?

I've looked at Linq-to-Datasets and Linq-to-XSD but they don't really seem to work directly with the Visual Studio DataSet.xsd files.

EDIT: I actually found a great link for this: link text but I can't seem to figure out what to do if I want to query on related tables.

    Dim taFields As New TestDSTableAdapters.FieldTableAdapter()
    Dim fields = taFields.GetData()

    Dim results = From f In fields Select f

    For Each field In results
        Response.Write(field.FieldID & " " & field.Label & " " & field.FieldTypeRow.FieldTypeLabel)
    Next

I get an "Object reference not set to an instance of an object." error when running the above code because, I guess, field.FieldTypeRow.FieldTypeLabel isn't actually part of the query of data. Do I have to create a method that returns data from that data also? I'm assuming this would be the case (that taFields.GetData has to return all the FieldType data results too if I'm going to reference it - in Linq to SQL it does all this for me so it's a little disappointing)

+2  A: 

A DataSet is just a container for your data, so you need to fill it first. LINQ to SQL will create SQL and go to the database for you...but when you're working with DataSets, you're using LINQ to Objects, which won't create SQL. So you need to make sure that all tables you need in the DataSet are filled before you start writing LINQ to query your DataSet.

I think you're looking for something along these lines:

Dim taFields As New TestDSTableAdapters.FieldTableAdapter()
Dim taFieldTypes As New TestDSTableAdapters.FieldTypesTableAdapter()

Dim ds As New TestDS

taFields.Fill(ds.Fields)
taFieldTypes.Fill(ds.FieldTypes)

Dim results = From f In ds.Fields Select f

For Each field In results
    Response.Write( _
        field.FieldID & " " & field.Label & " " & 
            field.FieldTypeRow.FieldTypeLabel)
Next
Kyralessa
A: 
   Dim taFields As New TestDSTableAdapters.FieldTableAdapter()
    Dim fields as TestDSTableAdapters.FieldsDataTable = taFields.GetData()

    Dim results = From f In fields Select f

    For Each field In results
        Response.Write(field.FieldID & " " & field.Label & " " & field.FieldTypeRow.FieldTypeLabel)
    Next

You forgot to set the type for fields. That is why yo uwere getting object reference problems. You do not have to create a new blank dataset.

This code still gave me the same error
EdenMachine
I had to change it to TestDS.FieldDataTable on the second line though because that's what the type is for taFields.GetData(). Kyralessa's code worked for me though - thanks!
EdenMachine