我正在创建一个C#T4模板来基于.edmx文件来构建一些类,到目前为止一直很好。我现在需要的是一种通过NavigationProperty访问它在数据库中连接的列名称的方法。
不久前,我意识到您可以在.edmx可视化设计器中,在特定NavigationProperty的映射详细信息下访问此信息:
所以基本上,如果在T4模板中;我已经有了一个我想要的NavigationProperty实例......我怎样才能获得它所连接的字段的名称? (在这种情况下为WeatherOnMondays
)
答案 0 :(得分:2)
答案来自:EF4: Get the linked column names from NavigationProperty of an EDMX
实现这一目标的两种方法:
// Obtain a reference to the navigation property you are interested in
var navProp = GetNavigationProperty();
// Load the metadata workspace
MetadataWorkspace metadataWorkspace = null;
bool allMetadataLoaded =loader.TryLoadAllMetadata(inputFile, out metadataWorkspace);
// Get the association type from the storage model
var association = metadataWorkspace
.GetItems<AssociationType>(DataSpace.SSpace)
.Single(a => a.Name == navProp.RelationshipType.Name)
// Then look at the referential constraints
var toColumns = String.Join(",",
association.ReferentialConstraints.SelectMany(rc => rc.ToProperties));
var fromColumns = String.Join(",",
association.ReferentialConstraints.SelectMany(rc => rc.FromProperties));
第二种方法:
NavigationProperty[] foreignKeys = entity.NavigationProperties
.Where(np => np.DeclaringType == entity &&
((AssociationType)np.RelationshipType).IsForeignKey).ToArray();
foreach (NavigationProperty foreignKey in foreignKeys)
{
foreach(var rc in GetSourceSchemaTypes<AssociationType>()
.Single(x => x.Name == foreignKey.RelationshipType.Name)
.ReferentialConstraints)
{
foreach(var tp in rc.ToProperties)
WriteLine(tp.Name);
foreach(var fp in rc.FromProperties)
WriteLine(fp.Name);
}
}
答案 1 :(得分:0)
如果您有NavigationProperty
,则其所连接的字段由属性ToEndMember
和FromEndMember
答案 2 :(得分:0)
此代码更简单。它在我的Visual Studio 2012上运行正常。可以在以下位置找到AssociationType类详细信息 http://msdn.microsoft.com/en-us/library/system.data.metadata.edm.associationtype.aspx和http://msdn.microsoft.com/en-us/library/system.data.metadata.edm.referentialconstraint.aspx。
<#@ template language="C#" debug="true" hostspecific="true"#>
<#@ include file="EF.Utility.CS.ttinclude"#>
<#
string inputFile = @"DomainModel.edmx";
MetadataLoader loader = new MetadataLoader(this);
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
{
foreach (NavigationProperty navProperty in entity.NavigationProperties)
{
AssociationType association = ItemCollection.GetItems<AssociationType>().Single(a => a.Name == navProperty.RelationshipType.Name);
string fromEntity = association.ReferentialConstraints[0].FromRole.Name;
string fromEntityField = association.ReferentialConstraints[0].FromProperties[0].Name;
string toEntity = association.ReferentialConstraints[0].ToRole.Name;
string toEntityField = association.ReferentialConstraints[0].ToProperties[0].Name;
}
}
#>
答案 3 :(得分:0)
请参阅http://brewdawg.github.io/Tiraggo.Edmx/,您可以从NuGet安装它。它提供edmx文件中的所有元数据,包括所有映射,每列的低级SQL数据类型,所有类型的东西,查看页面上的示例,您将看到它是多么容易。