使用LINQ to SQL读取DBML xml

问题描述:

我想遍历dbml的xml中的表。但是我很努力地去了Type元素。我如何使用LINQ to SQL来做到这一点?使用LINQ to SQL读取DBML xml

要获取元数据有关的DataContext模型我使用MappingSource属性DataContext的实例,例如,要获得一个模型中的表:

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

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

tablesMetaTable对象的ReadOnlyCollection。

+0

至于其他方面帮助 - 我花了两天绕着认识到,这是一个很好的答案! – Murph 2009-11-01 16:28:11

如果您真的需要必须使用(或希望)使用XML解析,需要注意的一点是LINQ到SQL中的命名空间。

下面是关于如何将<Table>节点下读出<Type>节点列表中选择一个样本:

// 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 
} 

希望有点帮助!

马克