我正在自定义 Entity Framework ASP.NET CRUD 模板,用于添加=>新脚手架项目...=>“使用 Entity Framework 的带 View 的 MVC 5 Controller ”。我还将 [ComplexType] 属性与用于实体属性的类一起使用(例如,[ComplexType] FullName 类用于我的 Customer 实体类中的 SpouseFullName 属性)。
public class Customer
{
public string CustomerNumber { get; set; }
public FullName SpouseFullName { get; set; }
}
[ComplexType]
public class FullName
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public FullName()
{
FirstName = "";
MiddleName = "";
LastName = "";
}
}
我希望能够在搭建脚手架时迭代我的 [ComplexType] 中每个属性的属性元数据。例如:
<#
IEnumerable<PropertyMetadata> properties = ModelMetadata.Properties;
foreach (PropertyMetadata property in properties)
{
// Is this a [ComplexType]?
if(property.IsComplexType)
{
// Iterate over metatdata here.
}
}
理想情况下,我希望能够得到 IEnumerable<PropertyMetadata>
我的 [ComplexType] 中包含的属性。想法?
最佳答案
想通了。我希望有更优雅的东西,但这行得通:
<#
IEnumerable<PropertyMetadata> properties = ModelMetadata.Properties;
foreach (PropertyMetadata property in properties)
{
if(property.IsComplexType)
{
System.Reflection.Assembly myAssembly = System.Reflection.Assembly.LoadFile("C:\\myFullAssemblyPath\\bin\\Release\\myAssembly.dll");
Type myType = myAssembly.GetType(property.TypeName);
if(myType == null)
{
#>
<th>TODO: Unable to render complex type (cannot load class from assembly). </th>
<#
}
else
{
foreach(var currentComplexProperty in myType.GetProperties())
{
string fullComplexName = property.PropertyName + "." + currentComplexProperty.Name;
#>
<th id="<#= fullComplexName #>">
<#= fullComplexName #>
</th>
<#
}
}
}
}
#>
这使用反射加载复杂类型的程序集,不需要引用。一旦你有了它,你就可以获取类型并迭代属性。
关于c# - 迭代 T4 脚手架中的 [ComplexType] 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42911190/