1

I want to iterate through the tables in a dbml's xml. But i'm struggling to get to the Type elements. How would I do it using LINQ to SQL?

2 Answers 2

1

To get meta-data about a DataContext model I use the MappingSource property of a DataContext instance, for example, to get the tables on a model:

var ctx = new YourDataContext();
var tables = ctx.Mapping.MappingSource.GetModel(ctx.GetType()).GetTables();

foreach (var table in tables)
{
   // table.TableName
}

tables is a ReadOnlyCollection of MetaTable objects.

Sign up to request clarification or add additional context in comments.

1 Comment

As a help to others - it took me two goes round to realise that this is a good answer!
1

If you really must (or want to) use XML parsing, the point to watch out for is the namespace in LINQ-to-SQL.

Here's a sample on how to read out the list of <Type> nodes under the <Table> node:

// create a XmlDocument
XmlDocument doc = new XmlDocument();
doc.Load(@"path-to-your-model.dbml");

// define the namespace to use
XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
mgr.AddNamespace("ns", "http://schemas.microsoft.com/linqtosql/dbml/2007");

// grab the list of all "type" nodes under a "table" node
XmlNodeList types = doc.SelectNodes("/ns:Database/ns:Table/ns:Type", mgr);

// iterate over all nodes found
foreach (XmlNode node in types)
{
   string name = node.Attributes["Name"].Value;
   // or do whatever else you need / want to do here
}

Hope that helps a bit!

Marc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.