我正在尝试编写T4模板来为我的模型类生成自定义视图,模型类位于另一个Assembly中,映射基于EF6 fluent API。
目前,我正在使用反射来获取属性的名称和类型,我的问题是如何阅读ModelConfiguration?例如,获取主键和相关模型的外键等。
答案 0 :(得分:4)
示例访问模型。注意DataSpace具有其他枚举值
public void EFTools2Test()
{
var context = new MyContext("MYConnie");
ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext;
MetadataWorkspace workspace = objContext.MetadataWorkspace;
IEnumerable<EntityType> managedTypes = workspace.GetItems<EntityType>(DataSpace.OSpace);
var result = new List<Type>();
foreach (var managedType in managedTypes) {
Console.WriteLine(managedType.FullName);
foreach ( var p in managedType.Properties) {
Console.WriteLine(p.Name );
}
}
}
public void EFToolsTest() {
// http://msdn.microsoft.com/en-us/library/system.data.metadata.edm.dataspace(v=vs.110).aspx
var context = new MyContext("MYConnie");
ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext;
MetadataWorkspace workspace = objContext.MetadataWorkspace;
var xyz = workspace.GetItems<EntityType>(DataSpace.SSpace);
foreach (var ET in xyz) {
foreach (var sp in ET.Properties) {
Debug.WriteLine(sp.Name + ":" + sp.MaxLength);// just as an example
}
}
}