1

Is there an easy way to have LINQ iterate through each of the fields in a table and get field properties such as the field name? Basically, I want to just create a simple xml document that represents the db schema like so:

 <report>
      <nameoffirsttable>
           <field1name>field1data</field1name>
           <field2name>field2data</field2name>
           ...
           <field234name>field234data</field234name>
      </nameoffirsttable>
      <nameofsecondtable>
           ...
      </nameofsecondtable>
      <anothersecondtable>
           ...
      </anothersecondtable>
 </report>

So far, all the examples I have seen in web searches have shown explicit references to named fields.

Fritz Fox
  • 13
  • 3
  • A `System.Data.DataSet` has methods `WriteXml` and `WriteXmlSchema` that can write out tables in a DataSet as XML. That is not LINQ obviously so I mention it in a comment, not as an answer, but maybe it suffices for your needs. – Martin Honnen Oct 13 '11 at 18:02

1 Answers1

2

This will produce the schema you outlined using LINQ:

XElement report = new XElement("report", 
MyDataContext.Mapping.GetTables()
   .Select(i => 
      new XElement(i.TableName, 
          i.RowType.DataMembers
          .Select(j => new XElement(j.Name, j.DeclaringType.Type.Name))));

Just make sure to reference System.Data.Linq and System.Xml.Linq.

Joe Mancuso
  • 2,099
  • 1
  • 16
  • 17
  • Thanks! Very nice example of how to iterate through the schema. Still kinda tricky to also correlate the data, instead of using the field's table name (j.DeclaringType.Type.Name). However answered my question and helped me know what to search for! – Fritz Fox Oct 20 '11 at 16:31