Fritz Fox
Fritz Fox

Reputation: 13

Using LINQ to iterate through a database and generate a generic XML layout of schema + data

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.

Upvotes: 1

Views: 104

Answers (1)

Joe Mancuso
Joe Mancuso

Reputation: 2129

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.

Upvotes: 2

Related Questions