开发者

Read DBML xml with LINQ to SQL

开发者 https://www.devze.com 2022-12-10 03:20 出处:网络
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? To get meta-data about a DataContext model I

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?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消