2

我正在自定义用于 Add=>New Scaffolded Item...=>“MVC 5 Controller with views, using Entity Framework”的 Entity Framework ASP.NET CRUD 模板。我还将 [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] 中包含的属性。想法?

4

1 回答 1

1

弄清楚了。我希望有更优雅的东西,但这有效:

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

这使用反射加载复杂类型的程序集,不需要引用。一旦你有了它,你就可以获取类型并迭代属性。

于 2017-03-27T14:34:09.570 回答